老师 我有个问题

来源:3-11 编程练习

木子小可爱

2019-10-12 12:22:41

//老师有个问题 如果我要用调用fill()方法,里面是有宽度和高度吗,像moveTo() 和lineTo()这种不可以,除非用了那个closePath(),就可以用哪个fill的方法填充

<!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 canvas=document.getElementById('canvas');

     var ctx=canvas.getContext('2d');

     //头部

     ctx.fillStyle='rgba(255,204,153,.5)';

     //ctx.strokeRect(300,200,200,150);

     ctx.fillRect(300,200,200,150);

    

     //左眼

     ctx.beginPath();

     ctx.arc(360,250,20,0,2*Math.PI,true);

     ctx.stroke()

     ctx.fillStyle='#000000'

     ctx.fill();

     //右眼

     ctx.beginPath();

     ctx.arc(440,250,20,0,2*Math.PI,true);

     ctx.stroke();

     ctx.fillStyle='#000000'

     ctx.fill();

     //嘴巴

     ctx.beginPath();

     //ctx.strokeRect(370,300,60,30)

     ctx.fillStyle='#cc0000';

     ctx.fillRect(370,300,60,30);

     

     //left耳朵

     ctx.beginPath();

     ctx.fillStyle='#FFFF66';

     ctx.fillRect(270,230,30,60);

     //ctx.strokeRect(270,230,30,60);

    //right耳朵

     ctx.beginPath();

     ctx.fillStyle='#FFFF66';

     ctx.fillRect(500,230,30,60);

     //ctx.strokeRect(500,230,30,60);

     //left line

     ctx.beginPath();

     ctx.moveTo(300,80);

     ctx.lineTo(380,200);

     ctx.lineWidth=5;

     ctx.strokeStyle="#FFCC66"

     ctx.stroke()

     //right line

     ctx.beginPath();

     ctx.moveTo(500,80);

     ctx.lineTo(420,200);

     ctx.lineWidth=5;

     ctx.strokeStyle="#FFCC66"

     ctx.stroke()

     //body

     ctx.beginPath();

     ctx.fillStyle='#FF99CC';

     ctx.fillRect(340,350,120,200);

     //ctx.strokeRect(340,350,120,200);

     //left hand

     ctx.beginPath();

     ctx.fillStyle='#669966';

     ctx.fillRect(140,430,200,20);

     //ctx.strokeRect(140,430,200,20);

     //rigth hand

     ctx.beginPath();

     ctx.fillStyle='#669966';

     ctx.fillRect(460,430,200,20);

     //ctx.strokeRect(460,430,200,20);

     //left foot

     ctx.beginPath();

     ctx.fillStyle='#669966';

     ctx.fillRect(360,550,20,200);

     //ctx.strokeRect(360,550,20,200);

     //right foot

     ctx.beginPath();

     ctx.fillStyle='#669966';

     ctx.fillRect(420,550,20,200);

     //ctx.strokeRect(420,550,20,200);

</script>

</body>

</html>


写回答

1回答

好帮手慕夭夭

2019-10-12

你好同学,fill()是设置填充颜色的,它没有宽高。如果是绘制的是线条,则不可以使用fill()。只有绘制的是形状,才可以使用fill()。使用moveTo, lineTo绘制的是线条,所以可以通过closePath闭合成一个形状 ,这样就可以使用填充了哦。

直接绘制的形状是可以使用填充的:

http://img.mukewang.com/climg/5da19ad1098afa0601940163.jpg

如果是绘制了几条线,组成的一个形状,那么可以closePath闭合路径,才可以使用填充,与宽高无关:

http://img.mukewang.com/climg/5da19af8091f358a02360175.jpg

祝学习愉快,望采纳。

0

0 学习 · 6815 问题

查看课程