用香草 javascript 擦除在 canvas 元素中绘制的线条?
Erase line drawn in canvas element with vanilla javascript?
我正在尝试在我的 canvas 中实现橡皮擦功能,我可以使用此功能绘图:
canvas = document.createElement("canvas")
context = canvas.getContext("2d")
function reposition(event) {
coords.x = event.clientX - canvas.getBoundingClientRect().left;
coords.y = event.clientY - canvas.getBoundingClientRect().top;
context.arc
}
function draw(event) {
context.beginPath();
context.lineWidth = "30";
context.lineCap = "square";
context.strokeStyle = "#999999"
context.moveTo(coords.x, coords.y);
reposition(event);
context.lineTo(coords.x, coords.y);
context.stroke();
}
我可以更改此设置,而不是绘制彩色笔划,而是擦除 canvas 以使绘制的线条透明吗?
所以这里起作用的是将 GlobalCompositeOperation = 'destination-out';
添加到我的函数中
最终函数:
function draw(event) {
context.beginPath();
GlobalCompositeOperation = 'destination-out';'
context.lineWidth = "30";
context.lineCap = "square";
context.strokeStyle = "#999999"
context.moveTo(coords.x, coords.y);
reposition(event);
context.lineTo(coords.x, coords.y);
context.stroke();
}```
我正在尝试在我的 canvas 中实现橡皮擦功能,我可以使用此功能绘图:
canvas = document.createElement("canvas")
context = canvas.getContext("2d")
function reposition(event) {
coords.x = event.clientX - canvas.getBoundingClientRect().left;
coords.y = event.clientY - canvas.getBoundingClientRect().top;
context.arc
}
function draw(event) {
context.beginPath();
context.lineWidth = "30";
context.lineCap = "square";
context.strokeStyle = "#999999"
context.moveTo(coords.x, coords.y);
reposition(event);
context.lineTo(coords.x, coords.y);
context.stroke();
}
我可以更改此设置,而不是绘制彩色笔划,而是擦除 canvas 以使绘制的线条透明吗?
所以这里起作用的是将 GlobalCompositeOperation = 'destination-out';
添加到我的函数中
最终函数:
function draw(event) {
context.beginPath();
GlobalCompositeOperation = 'destination-out';'
context.lineWidth = "30";
context.lineCap = "square";
context.strokeStyle = "#999999"
context.moveTo(coords.x, coords.y);
reposition(event);
context.lineTo(coords.x, coords.y);
context.stroke();
}```