HTMLCanvas画布重叠(菜鸡记录)

本文记录使用HTMLCanvas进行图形绘制时如何实现背景保留和错误清除。通过创建两层画布,一层用于背景,一层用于动态绘画,确保清除操作不会影响背景。示例中展示了在背景图上画圆和矩形,然后清除矩形但保留背景的方法,类似绘画软件的图层管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

菜鸡记录不常用到的东西,免得以后如果再遇到要重看一遍,有问题请帮忙指出一下,谢谢~~

目的:在有背景的图上作画,画错的地方要清除,背景要保留,不能也清除。

指定某张图为背景,在上面画图,一圆一框

代码如下:        

<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,所以坐标需要稍改动

可以看到矩形没了,背景图还在

如果需要圆是完整的话,可以重绘一次圆,或者再继续加图层,一层背景一层圆一层框,操作就像是用绘画软件画画时眼睛鼻子头发在不同的图层一样,方便修改和不影响已经画好的地方 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值