首页 > 解决方案 > HTML5画布:角度> 2 PI的逆时针弧

问题描述

我试图弄清楚为什么在顺时针和逆时针绘制圆弧时,角度 > 2 PI 不会给出相同的结果。

看这个代码片段,在第一行,我画了“顺时针”3 条红色弧线,起始角为 0,结束角为 PI,2*PI 和 3*PI。然后我用相同的参数绘制“逆时针”3个蓝色弧线。

第三个结果让我感到困惑......有人可以向我解释一下吗?

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

// CLOCKWISE, angle = PI
ctx.beginPath();
ctx.arc(50, 50, 40, 0, Math.PI, false);
ctx.closePath();
ctx.stroke();
ctx.fillStyle = "red";
ctx.fill();

// CLOCKWISE, angle = 2 PI
ctx.beginPath();
ctx.arc(150, 50, 40, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.stroke();
ctx.fillStyle = "red";
ctx.fill();

// CLOCKWISE, angle = 3 PI
ctx.beginPath();
ctx.arc(250, 50, 40, 0, 3 * Math.PI, false);
ctx.closePath();
ctx.stroke();
ctx.fillStyle = "red";
ctx.fill();

// COUNTERCLOCKWISE, angle = PI
ctx.beginPath();
ctx.arc(50, 150, 40, 0, Math.PI, true);
ctx.closePath();
ctx.stroke();
ctx.fillStyle = "blue";
ctx.fill();

// COUNTERCLOCKWISE, angle = 2 PI
ctx.beginPath();
ctx.arc(150, 150, 40, 0, 2 * Math.PI, true);
ctx.closePath();
ctx.stroke();
ctx.fillStyle = "blue";
ctx.fill();

// COUNTERCLOCKWISE, angle = 3 PI
ctx.beginPath();
ctx.arc(250, 150, 40, 0, 3 * Math.PI, true);
ctx.closePath();
ctx.stroke();
ctx.fillStyle = "blue";
ctx.fill();
<canvas id="myCanvas" width="350" height="250" style="border:1px solid #d3d3d3;"/>

标签: javascripthtmlcanvas

解决方案


当您逆时针方向时,0 之后是 2PI。你应该试试这个:

// COUNTERCLOCKWISE, angle = 3 PI
ctx.beginPath();
ctx.arc(250, 150, 40, 2 * Math.PI, 0, true);
ctx.closePath();
ctx.stroke();
ctx.fillStyle = "blue";
ctx.fill();
更新:

在 OP 发表评论后,我添加了一个动画演示:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
let delta = 0;

function Draw(){
 requestAnimationFrame(Draw) 
 delta+= .01; 
ctx.clearRect(0,0,c.width,c.height)

// CLOCKWISE: animating the end point
ctx.beginPath();
ctx.arc(50, 50, 40, 0, delta, false);
ctx.closePath();
ctx.stroke();


// CONTERCLOCKWISE, animating the start point
ctx.beginPath();
ctx.arc(150, 50, 40, 0,-delta, true);
ctx.closePath();
ctx.stroke();

}

Draw()
<canvas id="myCanvas" width="350" height="250" style="border:1px solid #d3d3d3;"/>


推荐阅读