Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript HTML5 Canvas drawing transparent circles

I need to have a function to draw several circles on canvas starting with mousedown at center=x,y and dragging mouse to deltaX,deltaY thus creating radius r, for each circle. The circles cannot have a fill (need them transparent) so the user can see clearly where the circles intercept. My current code draws circles WHILE the mouse is dragged, and that's expected, but it also LEAVES those extra circles behind. I need to leave only the circle on mouseup. Any help is appreciated. Thank you :).

<html>

<head>

</head>

<body style="margin:0">
<canvas id="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.beginPath();
  context.arc(nStartX, nStartY, radius, 0, Math.PI*2);
  context.strokeStyle="#000000";
  //context.fillStyle="#FFFFFF";
  context.fillStyle = 'rgba(0, 0, 0, 0)';
  context.stroke();
  context.fill();
}
var stopPoint = function(e){
  //context.clip();
  //context.clearRect(0, 0, canvas.width, canvas.height);
  bIsDrawing = false;
}
canvas.addEventListener('mousedown',putPoint);
canvas.addEventListener('mousemove',drawPoint);
canvas.addEventListener('mouseup',stopPoint);

</script>
</body>

</html>
like image 578
Sobra Avatar asked Apr 14 '16 12:04

Sobra


1 Answers

You need to keep track of the circles (and other objects) that you've drawn - one way would be to push them into an array on mouseup. Then each draw should be preceded by a canvas clear and redraw of the saved circles.

var circles = [];
...

Clearing the canvas

...
radius = Math.sqrt(nDeltaX * nDeltaX + nDeltaY * nDeltaY)
context.clearRect(0, 0, canvas.width, canvas.height);
...

Drawing saved circles

...
context.fill();
// drawing saved circles
circles.forEach(function(circle){
    context.beginPath();
    context.arc(circle.nStartX, circle.nStartY, circle.radius, 0, Math.PI*2);
    context.strokeStyle="#000000";
    context.fillStyle="#FFFFFF";
    context.fillStyle = 'rgba(0, 0, 0, 0)';
    context.stroke();
    context.fill();
})
...

Saving completed circles

...
bIsDrawing = false;
// saving completed circles
var nDeltaX = nStartX - e.clientX;
var nDeltaY = nStartY - e.clientY;
radius = Math.sqrt(nDeltaX * nDeltaX + nDeltaY * nDeltaY);
circles.push({ nStartX: nStartX, nStartY: nStartY, radius: radius });
...

Fiddle - https://jsfiddle.net/9x77sg2h/

like image 171
potatopeelings Avatar answered Nov 15 '22 05:11

potatopeelings