Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Canvas Rotate Image

jQuery('#carregar').click(function() {   var canvas    = document.getElementById('canvas');   var image   = document.getElementById('image');   var element = canvas.getContext("2d");   element.clearRect(0, 0, canvas.width, canvas.height);   element.drawImage(image, 0, 0, 300, 300); }); 

jsfiddle.net/braziel/nWyDE/

I have a problem to rotate an image 90 ° to the right or to the left.

I use an image on the canvas, the same screen will have several canvas equal to that of the example, but I left it as close as possible to the project.

I ask, how do I rotate the image 90 ° to the left or right when I click "Rotate Left" and "Rotate Right"?

I tried several codes on the internet but none worked.

like image 504
Max William Vitorino Avatar asked Jul 01 '13 19:07

Max William Vitorino


People also ask

Can you rotate an image in canvas?

Rotate your photo 90 degrees to the right by clicking the Rotate right button. Flip your photo along its horizontal axis by clicking the Horizontal flip button. Flip your photo along its vertical axis by clicking the Vertical flip button.

How do you rotate a canvas in HTML?

Introduction to JavaScript rotate() canvas APIThe rotate() method allows you to rotate a drawing object on the canvas. The rotate() method accepts a rotation angle in radians. If the angle is positive, the rotation is clockwise. In case the angle is negative, the rotation is counterclockwise.

How do you rotate shapes in canvas?

To rotate a shape around its own center, you must first translate the canvas to the center of the shape, then rotate the canvas, then translate the canvas back to 0,0, and then draw the shape. This example first translates (moves) the center of the canvas to the center of the square (cx, cy).


2 Answers

You can use canvas’ context.translate & context.rotate to do rotate your image

enter image description here

Here’s a function to draw an image that is rotated by the specified degrees:

function drawRotated(degrees){     context.clearRect(0,0,canvas.width,canvas.height);      // save the unrotated context of the canvas so we can restore it later     // the alternative is to untranslate & unrotate after drawing     context.save();      // move to the center of the canvas     context.translate(canvas.width/2,canvas.height/2);      // rotate the canvas to the specified degrees     context.rotate(degrees*Math.PI/180);      // draw the image     // since the context is rotated, the image will be rotated also     context.drawImage(image,-image.width/2,-image.width/2);      // we’re done with the rotating so restore the unrotated context     context.restore(); } 

Here is code and a Fiddle: http://jsfiddle.net/m1erickson/6ZsCz/

<!doctype html> <html> <head> <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css --> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>  <style>     body{ background-color: ivory; }     canvas{border:1px solid red;} </style>  <script> $(function(){      var canvas=document.getElementById("canvas");     var ctx=canvas.getContext("2d");      var angleInDegrees=0;      var image=document.createElement("img");     image.onload=function(){         ctx.drawImage(image,canvas.width/2-image.width/2,canvas.height/2-image.width/2);     }     image.src="houseicon.png";      $("#clockwise").click(function(){          angleInDegrees+=30;         drawRotated(angleInDegrees);     });      $("#counterclockwise").click(function(){          angleInDegrees-=30;         drawRotated(angleInDegrees);     });      function drawRotated(degrees){         ctx.clearRect(0,0,canvas.width,canvas.height);         ctx.save();         ctx.translate(canvas.width/2,canvas.height/2);         ctx.rotate(degrees*Math.PI/180);         ctx.drawImage(image,-image.width/2,-image.width/2);         ctx.restore();     }   }); // end $(function(){}); </script>  </head>  <body>     <canvas id="canvas" width=300 height=300></canvas><br>     <button id="clockwise">Rotate right</button>     <button id="counterclockwise">Rotate left</button> </body> </html> 
like image 95
markE Avatar answered Sep 21 '22 13:09

markE


Quickest 2D context image rotation method

A general purpose image rotation, position, and scale.

// no need to use save and restore between calls as it sets the transform rather  // than multiply it like ctx.rotate ctx.translate ctx.scale and ctx.transform // Also combining the scale and origin into the one call makes it quicker // x,y position of image center // scale scale of image // rotation in radians. function drawImage(image, x, y, scale, rotation){     ctx.setTransform(scale, 0, 0, scale, x, y); // sets scale and origin     ctx.rotate(rotation);     ctx.drawImage(image, -image.width / 2, -image.height / 2); }  

If you wish to control the rotation point use the next function

// same as above but cx and cy are the location of the point of rotation // in image pixel coordinates function drawImageCenter(image, x, y, cx, cy, scale, rotation){     ctx.setTransform(scale, 0, 0, scale, x, y); // sets scale and origin     ctx.rotate(rotation);     ctx.drawImage(image, -cx, -cy); }  

To reset the 2D context transform

ctx.setTransform(1,0,0,1,0,0); // which is much quicker than save and restore 

Thus to rotate image to the left (anti clockwise) 90 deg

drawImage(image, canvas.width / 2, canvas.height / 2, 1, - Math.PI / 2); 

Thus to rotate image to the right (clockwise) 90 deg

drawImage(image, canvas.width / 2, canvas.height / 2, 1, Math.PI / 2); 

Example draw 500 images translated rotated scaled

var image = new Image;  image.src = "https://i.stack.imgur.com/C7qq2.png?s=328&g=1";  var canvas = document.createElement("canvas");  var ctx = canvas.getContext("2d");  canvas.style.position = "absolute";  canvas.style.top = "0px";  canvas.style.left = "0px";  document.body.appendChild(canvas);  var w,h;  function resize(){ w = canvas.width = innerWidth; h = canvas.height = innerHeight;}  resize();  window.addEventListener("resize",resize);  function rand(min,max){return Math.random() * (max ?(max-min) : min) + (max ? min : 0) }  function DO(count,callback){ while (count--) { callback(count) } }  const sprites = [];  DO(500,()=>{      sprites.push({         x : rand(w), y : rand(h),         xr : 0, yr : 0, // actual position of sprite         r : rand(Math.PI * 2),         scale : rand(0.1,0.25),         dx : rand(-2,2), dy : rand(-2,2),         dr : rand(-0.2,0.2),      });  });  function drawImage(image, spr){      ctx.setTransform(spr.scale, 0, 0, spr.scale, spr.xr, spr.yr); // sets scales and origin      ctx.rotate(spr.r);      ctx.drawImage(image, -image.width / 2, -image.height / 2);  }  function update(){      var ihM,iwM;      ctx.setTransform(1,0,0,1,0,0);      ctx.clearRect(0,0,w,h);      if(image.complete){        var iw = image.width;        var ih = image.height;        for(var i = 0; i < sprites.length; i ++){            var spr = sprites[i];            spr.x += spr.dx;            spr.y += spr.dy;            spr.r += spr.dr;            iwM = iw * spr.scale * 2 + w;            ihM = ih * spr.scale * 2 + h;            spr.xr = ((spr.x % iwM) + iwM) % iwM - iw * spr.scale;            spr.yr = ((spr.y % ihM) + ihM) % ihM - ih * spr.scale;            drawImage(image,spr);        }      }          requestAnimationFrame(update);  }  requestAnimationFrame(update);
like image 36
Blindman67 Avatar answered Sep 22 '22 13:09

Blindman67