Skip to content
Advertisement

Drawing A Rotated Path2D Object on canvas

I have a canvas where i want to draw a rotated svg.

In order to achieve this, i created a Path2D object and used the context.fill() option to draw the svg.

Moreover, I used context.translate(x , y) inorder to position the svg.

Now, the issue i how to rotate this?

I found some solutions where it stated that first use context.translate(x , y) to set the transformation point and then use context.rotate(deg) to rotate.

Now, both the translate are in conflict.

Here is the code that I have tried so far. This code rotates the svg element. But from its top right corner. I want it to be rotated from center:

Codepen link – https://codepen.io/asiancat54x/pen/jOwyeaR

Here is the code snippet

JavaScript

Advertisement

Answer

I’d read about how transformations work in computer graphic (transformation matrices).

Here’s an article explaining it thoroughly: https://learnopengl.com/Getting-started/Transformations

Your issue as you stated is where the svg is rotated from – the transformation origin is not the center of the svg.

To change the transformation origin you can apply a translation after the rotation (Read to article to understand why).

JavaScript

I played around with it and this hit the spot although I’d recommend finding the actual thing that causes the origin to shift in the first place. (avoid using magic numbers – especially when applying transformations).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement