Canvas对象:JavaScript中的半圆形漏色

时间:2017-07-18 11:10:25

标签: javascript html canvas

您好我想了解canvas的开启和关闭功能的要点。 我注意到的是当我只使用一个打开和关闭画布功能时,对于2个单独的对象,一个矩形和一个半圆。颜色开始泄漏如图所示:

figure 1:result noticed

我的期望如下图2.具有一个打开和关闭画布功能:

figure 2 result expected

代码如下所述

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();

1 个答案:

答案 0 :(得分:0)

函数ctx.beginPath通过删除所有现有路径点和笔划来创建新路径对象

函数ctx.closePath创建一条线,从添加到当前路径的最后一个点到前一个ctx.moveToctx.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