Skip to content Skip to sidebar Skip to footer

Html Canvas Draw A Circle On Mouse Click And Drag It Untill The Required Radius Is Obtained

Im new to canvas and i was playing around with it. I wanted to draw a circle on mouse click and radius of circle should be decided by mouse drag (similar to drawing circle in Pain

Solution 1:

the general ideia is that you have to take 2 points, the one there circle center will be (this is where the user presses the mouse), and the current point, where the mouse is moving

the distance between the 2 points will be the radius, and is given by the Pythagorean theorem h^2 = c^2 + c^2 so:

  • onmousedown save that point as center
  • omousemove calculate the distance to center and use as radius
  • omouseup stop the operation/animation

here is some sample code, modify to your needs

<html><head></head><bodystyle="margin:0"><canvasid="canvas"width="500"height="500"style="border:1px solid"></canvas><script>var canvas=document.getElementById('canvas');
var context=canvas.getContext('2d');
var radius=50;
var nStartX = 0;
var nStartY = 0;
var bIsDrawing = false;
var putPoint = function(e){
  nStartX = e.clientX;nStartY = e.clientY;
  bIsDrawing = true;
  radius = 0;
}
var drawPoint = function(e){
  if(!bIsDrawing)
    return;
  var nDeltaX = nStartX - e.clientX;
  var nDeltaY = nStartY - e.clientY;
  radius = Math.sqrt(nDeltaX * nDeltaX + nDeltaY * nDeltaY)
  context.clearRect(0, 0, canvas.width, canvas.height);
  context.beginPath();
  context.arc(nStartX, nStartY, radius, 0, Math.PI*2);
  context.fill();
}
var stopPoint = function(e){
  bIsDrawing = false;
}
canvas.addEventListener('mousedown',putPoint);
canvas.addEventListener('mousemove',drawPoint);
canvas.addEventListener('mouseup',stopPoint);

</script></body></html>

Post a Comment for "Html Canvas Draw A Circle On Mouse Click And Drag It Untill The Required Radius Is Obtained"