无法在HTML Canvas中旋转笔触

时间:2016-12-14 07:58:17

标签: javascript html canvas html5-canvas

我正在尝试创建一个部分环并旋转它。

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

var w = c.width;
var h = c.height;
var cx = w/2;
var cy = h/2;
var sw = 20;

var pi = Math.PI;
var r = Math.min(w, h)/2 - sw/2;
var k = 0;
var i = pi*1/30;

x.lineWidth = sw;
x.lineCap = "butt";
x.beginPath();
x.arc(cx, cy, r, -pi*2, -pi/16);
x.rotate(pi*1/3); // IS NOT TAKING EFFECT
x.stroke();
<canvas id="c" width="100px" height="100px"></canvas>

如您所见,在最后一部分中,在致电stroke()之前,我执行了:

x.rotate(pi*1/3);

但是我无法在最终渲染中看到旋转。我做错了什么?

1 个答案:

答案 0 :(得分:1)

添加路径时,变换的当前状态将在添加时使用。之后路径不会改变。

所以在这里,只需在添加更多路径数据之前进行旋转(在这种情况下,您还需要使用translate从枢轴/旋转点绘制圆弧)。

&#13;
&#13;
var c = document.getElementById("c");
var x = c.getContext("2d");

var w = c.width;
var h = c.height;
var cx = w/2;
var cy = h/2;
var sw = 20;

var pi = Math.PI;
var r = Math.min(w, h)/2 - sw/2;
var k = 0;
var i = pi*1/30;

x.lineWidth = sw;
x.lineCap = "butt";
x.beginPath();
x.translate(cx, cy);            // update matrix
x.rotate(pi*1/3);
x.arc(0, 0, r, -pi*2, -pi/16);  // uses current matrix
x.stroke();
&#13;
<canvas id="c" width="100px" height="100px"></canvas>
&#13;
&#13;
&#13;