菜鸡记录不常用到的东西,免得以后如果再遇到要重看一遍,有问题请帮忙指出一下,谢谢~~
目的:在有背景的图上作画,画错的地方要清除,背景要保留,不能也清除。
指定某张图为背景,在上面画图,一圆一框
代码如下:
<div>
<img id="mzsh_img" src="./mzsh.jpeg" />
<canvas id="canvas_background"></canvas>
</div>
<script>
var backgroundImg = document.getElementById("mzsh_img");
var canvasBackground = document.getElementById("canvas_background");
canvasBackground.width = backgroundImg.width;//设置画布大小和图片相同,否则画布有默认大小
canvasBackground.height = backgroundImg.height;
var ctx = canvasBackground.getContext("2d"); //ctx对画布做需要的操作
ctx.drawImage(backgroundImg, 0, 0);
ctx.stroke(); //确认绘制
ctx.lineWidth = 3;
ctx.arc(200,200,50,0,2*Math.PI);//圆
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle="red";
ctx.rect(200, 200, 100, 100);//矩形
ctx.stroke();
</script>
运行结果:
现在不想要矩形了,直接清除会是这样,背景没有了
ctx.clearRect(198, 198, 104, 104);//线粗3,所以坐标需要稍改动
要达到目的需要两层画布,一层放背景一层绘画
<img id="mzsh_img" src="./mzsh.jpeg" />
<canvas id="canvas_background"></canvas>
<canvas id="canvas_draw"></canvas>
JS代码
<script>
var backgroundImg = document.getElementById("mzsh_img");
var canvasBackground = document.getElementById("canvas_background");
canvasBackground.width = backgroundImg.width;//设置画布大小和图片相同,否则画布有默认大小
canvasBackground.height = backgroundImg.height;
canvasBackground.style.position = "absolute";//设置元素定位,使其可以堆叠
canvasBackground.style.zIndex = "-1";//设置堆叠顺序,数字小的在下方(后面的图层)
var ctx = canvasBackground.getContext("2d"); //ctx对画布做需要的操作
ctx.drawImage(backgroundImg, 0, 0);
ctx.stroke(); //确认绘制
var canvasDraw=document.getElementById("canvas_draw");
canvasDraw.style.zIndex = "1";
canvasDraw.width = backgroundImg.width;
canvasDraw.height = backgroundImg.height;
var ctxDraw=canvasDraw.getContext("2d");
ctxDraw.lineWidth = 3;
ctxDraw.arc(200,200,50,0,2*Math.PI);//圆
ctxDraw.stroke();
ctxDraw.beginPath();
ctxDraw.strokeStyle="red";
ctxDraw.rect(200, 200, 100, 100);//矩形
ctxDraw.stroke();
</script>
显示效果,和上面一样,但是在浏览器调试模式可以看到两个Canvas是重叠在一起的,而不是只有一层
再清除矩形框
ctxDraw.clearRect(198, 198, 104, 104);//线粗3,所以坐标需要稍改动
可以看到矩形没了,背景图还在
如果需要圆是完整的话,可以重绘一次圆,或者再继续加图层,一层背景一层圆一层框,操作就像是用绘画软件画画时眼睛鼻子头发在不同的图层一样,方便修改和不影响已经画好的地方