Andry
Andry

Reputation: 16845

Cannot rotate stroke in HTML Canvas

I am trying to create a partial annulus and rotate it.

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>

As you can see, in the last part, before calling stroke(), I perform:

x.rotate(pi*1/3);

However I cannot see the rotation in the final rendering. What am I doing wrong?

Upvotes: 0

Views: 105

Answers (1)

user1693593
user1693593

Reputation:

When adding paths the current state of the transform will be used at the point it is added. The path will not change afterwards.

So here, simply do the rotate before adding more path data (in this case you also need to use translate to draw the arc from pivot/rotation point).

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();
<canvas id="c" width="100px" height="100px"></canvas>

Upvotes: 1

Related Questions