Skip to content Skip to sidebar Skip to footer

Drawing A Circle Using Mouse Position

I am trying to draw a circle by clicking and dragging the mouse pointer. The way you would do in PowerPoint or something. The center of the circle is showing up in weird places and

Solution 1:

It happens because you're scaling your canvas using CSS. Remember, canvas dimensions are different from canvas CSS (style) dimensions.

A quick fix is to equalize them:

canvas.get(0).width = canvas.width();
canvas.get(0).height = canvas.height();

https://jsfiddle.net/h8t3hfa2/3/

varCircle = function() {
  this.start = [];
  this.end = [];
}
Circle.prototype.draw = function(canvas) {
  var me = this;

  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');
    var mid = me.getcenter();
    var rad = me.getradius();
    console.log(mid, rad);
    ctx.beginPath();
    console.log(mid['x'], mid['y']);
    ctx.arc(mid['x'], mid['y'], rad, 0, 360);
    ctx.stroke();
  }

};

Circle.prototype.getcenter = function() {
  var me = this;
  //Check the start and end are setvar centerX = (me.start['x'] + me.end['x']) / 2;
  var centerY = (me.start['y'] + me.end['y']) / 2;

  return {
    'x': centerX,
    'y': centerY
  };
};

Circle.prototype.getradius = function() {
  var me = this;
  var distX = Math.abs(me.start['x'] - me.end['x']);
  var distY = Math.abs(me.start['y'] - me.end['y']);

  return distX / 2;
};

var circle;
var canvas = $('#c');

// added only these two lines
canvas.get(0).width = canvas.width();
canvas.get(0).height = canvas.height();

$('#c').mousedown(function(event) {
  var parentOffset = $(this).offset();
  circle = newCircle();
  circle.start['x'] = event.pageX - parentOffset.left;
  circle.start['y'] = event.pageY - parentOffset.top;

});

$('#c').mouseup(function(event) {
  var parentOffset = $(this).offset();
  circle.end['x'] = event.pageX - parentOffset.left;
  circle.end['y'] = event.pageY - parentOffset.top;
  circle.draw(canvas[0]);

});
canvas {background-color: white;height: 100%;width: 100%;}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><canvasid='c'></canvas>

You should probably also add an onresize event handler to reset the canvas dimensions when the window size changes because you're using a fluid layout. Be careful, though, modifying either of the canvas dimensions (even to the original size) will cause the canvas to clear.

Solution 2:

Removing height: 100%; width: 100%; from styles fixes avoids the problem.

Off-topic, but I suggest editing getradius to use the min (or max) of distX and distY (instead of hardcoding distX) like the applications you mentioned.

Circle.prototype.getradius = function() {
  var me = this;
  var distX = Math.abs(me.start['x'] - me.end['x'])/2;
  var distY = Math.abs(me.start['y'] - me.end['y'])/2;

  returnMath.min(distX, distY);
};

Post a Comment for "Drawing A Circle Using Mouse Position"