您好我想了解canvas的开启和关闭功能的要点。 我注意到的是当我只使用一个打开和关闭画布功能时,对于2个单独的对象,一个矩形和一个半圆。颜色开始泄漏如图所示:
我的期望如下图2.具有一个打开和关闭画布功能:
代码如下所述
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.rect(30, 30, 50, 60);
ctx.fillStyle = "#FF0000";
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.arc(350,200,20,0,Math.PI*2,false);
ctx.fillStyle = "green";
ctx.fill();
ctx.closePath();
答案 0 :(得分:0)
函数ctx.beginPath
通过删除所有现有路径点和笔划来创建新路径对象
函数ctx.closePath
创建一条线,从添加到当前路径的最后一个点到前一个ctx.moveTo
或ctx.beginPath
它与ctx.beginPath
函数无关,并且什么都不做如果后跟ctx.beginPath
函数ctx.closePath
与以下
ctx.lineTo
相同
ctx.beginPath();
ctx.moveTo(100,100);
ctx.lineTo(200,200);
ctx.lineTo(100,200);
ctx.lineTo(100,100); // back to start
与
相同ctx.beginPath();
ctx.moveTo(100,100);
ctx.lineTo(200,200);
ctx.lineTo(100,200);
ctx.closePath(); // does the same as ctx.lineTo(100,100); // back to start
代码中的一些注释。
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.rect(30, 30, 50, 60);
ctx.fillStyle = "#FF0000";
ctx.fill();
ctx.closePath(); // <<< Not needed as you have already called fill
ctx.beginPath(); // <<< this deletes the previous path
ctx.arc(350,200,20,0,Math.PI*2,false);
ctx.fillStyle = "green";
ctx.fill();
ctx.closePath(); // <<< not needed