老师如何能控制眼和脑袋的层级关系,比如想放脑袋下面
来源:3-11 编程练习
陈立天
2020-08-18 09:25:30
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>canvas</title> <style> canvas{background-color:lightblue;} </style> </head> <body> <canvas id="canvas" width="800" height="800"> 您的浏览器不支持canvas </canvas> <script> //在此处写出代码 var mycanvas = document.getElementById("canvas"); var ctx = mycanvas.getContext("2d"); ctx.save(); ctx.fillStyle = '#FFB5C5' ctx.fillRect(250,150,300,150);//头部 ctx.stroke(); ctx.restore(); ctx.save(); ctx.beginPath(); ctx.fillStyle = 'yellow'; ctx.fillRect(225,175,25,75);//左耳朵 ctx.beginPath(); ctx.fillRect(550,175,25,75);//右耳朵 ctx.restore(); ctx.save() ctx.beginPath(); ctx.fillStyle = 'red'; ctx.fillRect(350,260,100,25);//嘴巴 ctx.restore(); ctx.save(); ctx.beginPath(); ctx.fillStyle = 'pink'; ctx.fillRect(300,300,200,250);//身体 ctx.restore(); ctx.save(); ctx.beginPath(); ctx.fillStyle = 'blue'; ctx.fillRect(50,375,250,25);//左臂 ctx.beginPath(); ctx.fillRect(500,375,250,25);//右臂 ctx.beginPath(); ctx.fillRect(350,550,25,200);//左腿 ctx.beginPath(); ctx.fillRect(420,550,25,200);//右腿 ctx.restore(); ctx.save() ctx.beginPath(); ctx.moveTo(350,150); ctx.lineTo(250,50);//左天线 ctx.strokeStyle ='orange' ctx.lineWidth = '4' ctx.stroke(); ctx.beginPath(); ctx.moveTo(450,150); ctx.lineTo(550,50);//右天线 ctx.fill(); ctx.stroke(); ctx.restore(); ctx.beginPath(); ctx.save(); ctx.arc(320,207.5,15,0,2*Math.PI,true);//左眼球 ctx.fillStyle = 'black'; ctx.fill(); ctx.beginPath(); ctx.arc(480,207.5,15,0,2*Math.PI,true);//右眼球 ctx.fill(); ctx.restore() </script> </body> </html>
1回答
同学你好,canvas绘图时,无法通过样式,比如z-index等来控制图层级,只能通过调整代码的顺序来改变层级。比如,先写绘制脑袋的代码,再写绘制眼睛的代码,那么眼睛就会在脑袋上面,反之先画眼睛再画脑袋,会让脑袋覆盖在眼睛上,这和现象中的画画很像,后画的内容会覆盖先画的内容。
如果我的回答帮到了你,欢迎采纳,祝学习愉快!
相似问题