Jump to content

Javascript rotation does not work


jar4563
 Share

Recommended Posts

Hi

I have been trying to figure out why javascript image rotation wont work. I'm testing the rotation demo in w3schools.com site but even that does not work. The more angle you put to the image the further it goes off from the screen. When it's supposed to rotate the rect from the middle the rect seems to orient 0,0

Here's link to the tutorial:

https://www.w3schools.com/tags/canvas_rotate.asp

 

Oh and that tutorial uses rect drawing but it's the same issued with drawImage()

 

Any ideas why it doesn't work? I use google chrome

 

thx!

Edited by jar4563
Link to comment
Share on other sites

The rotation will always be about the origin (0, 0). If you want to rotate about the centre of an object you must first translate the centre to the origin, do the rotation and translate back again.

Javascript rotation certainly does work. I don't find the w3schools site very good - incomplete and not fully up to date. I use Mozilla's site for reference and the occasional tutorial. They cover rotation very clearly on this page: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Transformations

Mozilla is good for finding out which browsers support newer features too.

Link to comment
Share on other sites

@grelf Thanks for the link

following the rotation example on that page I have this code now:

ctx.save();  

  // right rectangles, rotate from rectangle center
  // draw blue rect
  ctx.fillStyle = '#0095DD';
  ctx.fillRect(150, 30, 100, 100);  
  
  ctx.translate(200, 80); // translate to rectangle center 
                          // x = x + 0.5 * width
                          // y = y + 0.5 * height
  ctx.rotate((Math.PI / 180) * rotAngle); // rotate
  ctx.translate(-200, -80); // translate back
  

  ctx.restore();  



// Draw some text:
 ctx.font = "30px Arial";
 ctx.fillText("Pos: " + worldPos.x + " " + worldPos.y, 5, gameArea.canvas.height - 15);

 

But nothing happens. only if I remove the save() and restore() the rect rotates as supposed to but then it also rotates the text's position that I'm also drawing

What am I doing wrong?

Edited by jar4563
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...