0

I have an arc on a canvas that moves around wherever the mouse is. it is stroked onto the canvas with the color black. if the mouse goes over something black, the circle disappears. i would like it if the circle could change color, depending on what it is being drawn over. could anyone help me?

here is some code:

ctx.beginPath()
ctx.clearRect(0, 0, brush.prePos.x + brush.size*2, brush.prePos.y + brush.size*2)
ctx.arc(pos.x, pos.y, brush.size / 4, 0, Math.PI*2)
ctx.stroke()
ctx.closePath()
erkus
  • 69
  • 1
  • 4

2 Answers2

0

You can try different compositing modes, particularly XOR. From the MDN example:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.globalCompositeOperation = 'xor';
Sami Hult
  • 3,052
  • 1
  • 12
  • 17
0

@SamiHult's answer is a good answer. Using globalCompositeOperation will do the trick. Here comes a demo:

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let cw = canvas.width = 300,
  cx = cw / 2;
let ch = canvas.height = 300,
  cy = ch / 2;
  // the mouse
  let m = {}
  // draw a black circle
  ctx.beginPath();
  ctx.arc(100,100,45,0,2*Math.PI);
  ctx.fill();

canvas.addEventListener("mousemove",(evt)=>{
  m = oMousePos(canvas, evt);
  ctx.clearRect(0,0,cw,ch);
  
  // draw a circle stroked black following the mouse
  drawCircle(m);
  // draw a black circle
  ctx.beginPath();
  ctx.arc(100,100,45,0,2*Math.PI);
  ctx.fill();
  
  // the important part:
  ctx.globalCompositeOperation = "xor";
})


function drawCircle(p){
  ctx.beginPath();
  ctx.arc(p.x,p.y,10,0,2*Math.PI);
  ctx.stroke();
}

function oMousePos(canvas, evt) {
  var ClientRect = canvas.getBoundingClientRect();
  return { //objeto
    x: Math.round(evt.clientX - ClientRect.left),
    y: Math.round(evt.clientY - ClientRect.top)
  }
}
canvas {
 border:1px solid;  
}
<canvas id="canvas"></canvas>
enxaneta
  • 31,608
  • 5
  • 29
  • 42