Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
116
rated 0 times [  121] [ 5]  / answers: 1 / hits: 7167  / 10 Years ago, mon, june 2, 2014, 12:00:00

I have an HTML5 canvas which contains an image. Now I want to rotate this canvas by x degrees.



What I did was:



function getRadianAngle(degreeValue) {
return degreeValue * Math.PI / 180;
}

var rotateCanvas = function(canvas, image, degrees) {
var context = canvas.getContext('2d');
context.rotate(getRadianAngle(degrees));
context.drawImage(image, 0, 0);
return canvas;
}

var image = new Image();
image.onload = function() {
var canvas = document.createElement(canvas);
var context = canvas.getContext('2d');
var cw = canvas.width = image.width;
var ch = canvas.height = image.height;
context.drawImage(image, 0, 0, image.width, image.height);

rotateCanvas(canvas, image, 180);
}
image.src = // some image url;


This code does not work correctly.



How can I define a rotate function to rotate a canvas?



Edit: I do not want to use css because I need the canvas for further processing.


More From » html

 Answers
3

Rotating the canvas can be done with CSS, but that might mess up your page design if the canvas is rectangular rather than square.



It's probably better to rotate your image on the canvas.




  • Clear the existing canvas.

  • Translate to the rotation point--x=image.x+image.width/2,y=image.y+image.height/2.

  • Rotate.

  • drawImage(image,-image.width/2,-image.height/2



Example code and a Demo: http://jsfiddle.net/m1erickson/8uRaL/



BTW, the radians for your desired angles are:




  • 0 degrees == 0 radians

  • 90 degrees == Math.PI/2 radians

  • 180 degrees == Math.PI radians

  • 270 degrees == Math.PI*3/2 radians



Example code:



<!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 radians=0;

var img=new Image();
img.onload=start;
img.src=https://dl.dropboxusercontent.com/u/139992952/stackoverflow/cat.png;
function start(){
animate();
}


function animate(){
requestAnimationFrame(animate);
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(canvas.width/2,canvas.height/2);
ctx.rotate(radians);
ctx.drawImage(img,-img.width/2,-img.height/2);
ctx.restore();
radians+=Math.PI/180;
}


}); // end $(function(){});
</script>
</head>
<body>
<canvas id=canvas width=300 height=300></canvas>
</body>
</html>

[#44865] Sunday, June 1, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
margob

Total Points: 302
Total Questions: 89
Total Answers: 100

Location: Guadeloupe
Member since Sat, Jul 25, 2020
4 Years ago
;