我在画布上有一个弧形,可以在任何鼠标移动的地方移动。它以黑色描边到画布上。如果鼠标越过黑色,圆圈将消失。我希望圆是否可以改变颜色,具体取决于绘制的内容。有人可以帮我吗?
下面是一些代码:
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()
答案 0 :(得分:0)
您可以尝试使用其他compositing modes,尤其是XOR。在MDN示例中:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.globalCompositeOperation = 'xor';
答案 1 :(得分:0)
@SamiHult的答案很好。使用foldr
可以解决问题。这里有一个演示:
globalCompositeOperation
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;
}