[英]How to erase on canvas without erasing background
I have a canvas to which I drawimage()
to be a background. 我有一个画布,我
drawimage()
作为背景。
I have an eraser tool with which I want to be able to erase what I draw but not the image I have in the canvas. 我有一个橡皮擦工具,我希望能够擦除我绘制的内容,但不能删除画布中的图像。 I know can place the image as a separate element behind the canvas but that is not what I am after since I desire to save what is in the canvas as a image.
我知道可以将图像作为画布后面的单独元素放置,但这不是我想要的,因为我希望将画布中的内容保存为图像。
My drawing function is here: 我的绘图功能在这里:
function draw (event) {
if (event == 'mousedown') {
context.beginPath();
context.moveTo(xStart, yStart);
} else if (event == 'mousemove') {
context.lineTo(xEnd, yEnd);
} else if (event == 'touchstart') {
context.beginPath();
context.moveTo(xStart, yStart);
} else if (event == 'touchmove') {
context.lineTo(xEnd, yEnd);
}
context.lineJoin = "round";
context.lineWidth = gadget_canvas.radius;
context.stroke();
}
If I need to explain further I will. 如果我需要进一步解释,我会。
Thank you in advance. 先感谢您。
There are a few ways you can go about this. 有几种方法可以解决这个问题。
I'd recommend putting the image as the canvas's CSS "background-image". 我建议把图像作为画布的CSS“background-image”。 Then draw on the canvas as normal.
然后照常在画布上画画。
When you want to save the Canvas as an image, you will need to do a sequence of events: 如果要将Canvas保存为图像,则需要执行一系列事件:
ctx2.drawImage(can1, 0, 0)
// paint first canvas onto new canvas ctx2.drawImage(can1, 0, 0)
//将第一个画布绘制到新画布上 ctx.clearRect(0, 0, width, height)
// clear first canvas ctx.clearRect(0, 0, width, height)
//清除第一个画布 ctx.drawImage(background, 0, 0)
// draw image on first canvas ctx.drawImage(background, 0, 0)
//在第一个画布上绘制图像 ctx.drawImage(can2, 0, 0)
// draw the (saved) first canvas back to itself ctx.drawImage(can2, 0, 0)
//将(已保存的)第一个画布绘制回自身 This will let you have the best of both worlds. 这将让您拥有两全其美。
I saved the image path in the an array, when I cleared the canvas I call the init function again: 我将图像路径保存在数组中,当我清除画布时,我再次调用init函数:
$( ".clear_canvas" ).click(function() {
console.log("clear");
var canvas = document.getElementById("canvasMain"),
ctx=canvas.getContext("2d");
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
//load the image again
init(path,width,height);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.