This should be simple.. but can’t figure out :
I am using rotate function on the 1st rectangle, but i am getting the 2nd rectangle rotated ?? 🙁
Updated the code after Remmy Sharp’s answer. But now the box has disappeared. I simply want one of two boxes to rotate on their reg point.
Where is the problem ?
<!DOCTYPE HTML>
<html>
<head>
<style>
#myCanvas {
border: 1px solid #9C9898;
}
#myCanvas2 {
border: 1px solid #9C9898;
}
body {
margin: 0px;
padding: 0px;
}
</style>
<script>
window.onload = function() {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.beginPath();
context.rect(100, 100, 200, 100);
context.fillStyle = '#8ED6FF';
context.fill();
context.lineWidth = 5;
context.strokeStyle = 'black';
context.stroke();
context.rotate(20*Math.PI/180); //<<<1st rectange should rotate
var canvas2 = document.getElementById('myCanvas2');
var context2 = canvas2.getContext('2d') //<< updated as per Remmy Sharp's answer.
context2.beginPath();
context2.rect(200, 200, 200, 100);
context2.fillStyle = '#8ED6FF';
context2.fill();
context2.lineWidth = 5;
context2.strokeStyle = 'black';
context2.stroke();
//canvas2.rotate = 45
//context2.rotate(20*Math.PI/180)
};
</script>
</head>
<body>
<canvas id="myCanvas" width="578" height="500">
<canvas id="myCanvas2" width="400" height="200"></canvas>
</canvas>
</body>
</html>
No, you’re painting the canvas and the first rectangle when you do the first
context.stroke– this immediately paints the pixels.Then you’re transforming the coordinate system with the
context.rotate, and then any subsequent painting to the canvas uses the newly transformed coordinate system (and hence why the second paint is rotated).And the reason the second rectangle is rotated (even though you appear to have a second canvas) is…you have a typo:
Should read:
So
context2is actually the same as yourcontextvariable in your example.You’ll also notice that when you update the code with the above fix, the rotation is too much – you’ll want to translate the
0,0centre point before rotating to get the effect (I think) you want.Edited and continue debugging code
So there’s a bunch more problems in your code including:
Here’s the code fixed, and made the canvas’ smaller (and CSS bg of red so I could see them) and I added an animation to visualise the rotation on the second canvas: http://jsbin.com/ovefux/1/edit