V
V
vladislavstarkov2011-02-12 22:31:19
Canvas
vladislavstarkov, 2011-02-12 22:31:19

How to use rotate in HTML5 canvas?

What is the correct way to use the JS rotate method on the canvas element in HTML5?
If I just do context.rotate(0.05) then the image starts to move down some strange trajectory.
The task is simple: rotate the canvas object around its axis by 60 degrees.
Give an example.
UPD: What is wrong in this code?
function html5(){
// experimenting with HTML5 canvas
ctx.beginPath()
ctx.arc(110, 113, 105, 0, Math.PI);
ctx.linewidth = 10;
ctx.strokeStyle = '#000';
ctx.rotate(2); // < - reverse, we obviously need to add something else here...
ctx.stroke();
ctx.closePath();
}

Answer the question

In order to leave comments, you need to log in

5 answer(s)
P
Pavlo Ponomarenko, 2011-02-14
@TheShock

In the topic that you were given above, there is a whole paragraph about this:

If we want to rotate some object, for example, a picture, it is necessary to interact correctly with the rotate and translate methods, otherwise we will never get the picture to the right place. The easiest way is to select the center of the image with the axis of rotation and draw it in coordinates (-width/2, -height/2). For example, we want to unfold a 50x50 image located at coordinates 100:100. We specify translate at the coordinate 125:125 and draw the image at the coordinate -25:-25. The alternative is to use LibCanvas and the rotatedImage method (or drawImage in the near future) and take it easy.

Using LibCanvas, which can be downloaded from GitHub , it will look something like this:
canvas
  .getContext('2d-libcanvas')
  .drawImage({
      image: yourCanvas,
      from : [15, 40],
      angle: (60).degree()
  });

If you use the Number.prototype.degree extension from the topic, then your code might look like this:
function rotatedDrawImage (ctx, image, fromX, fromY, angle) {
    ctx.save();
    ctx.translate(fromX + image.width / 2, fromY + image.height / 2);
    ctx.rotate(angle.degree());
    ctx.translate(-(fromX + image.width / 2), -(fromY + image.height / 2));
    ctx.drawImage(image, fromX, fromY);
    ctx.restore();
}
rotatedDrawImage(canvas.getContext('2d'), yourCanvas, 15, 40, 60);

P
Pavlo Ponomarenko, 2011-02-14
@TheShock

If I just do context.rotate(0.05) then the image starts to move down some strange trajectory.

It revolves around the point 0:0

N
nikitammf, 2011-02-13
@nikitammf

One option is in " Canvas Transformation in Plain Language "

M
Max Kuznetsov, 2011-02-14
@pluseg

What does moving out mean? Before turning everything as it should display?
The angle you're doing rotate() from is 60 degrees = Math.PI / 3?

K
Keyten, 2012-06-18
@Keyten

And further. The rotate function takes an angle in radians, for degrees use deg / 180 * Math.PI.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question