Javascript 如何在 html 5 画布上旋转单个对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2677671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I rotate a single object on an html 5 canvas?
提问by Kappers
I'm trying to figure out how to rotate a single object on an html 5 canvas.
我想弄清楚如何在 html 5 画布上旋转单个对象。
For example: http://screencast.com/t/NTQ5M2E3Mzct- I want each one of those cards to be rotated at a different degree.
例如:http: //screencast.com/t/NTQ5M2E3Mzct- 我希望这些卡片中的每一张都以不同的角度旋转。
So far, all I've seen are articles and examples that demonstrate ways to rotate the entire canvas. Right now, I'm guessing I'll have to rotate the canvas, draw an image, and then rotate the canvas back to it's original position before drawing the second image. If that's the case, then just let me know! I just have a feeling that there's another way.
到目前为止,我所看到的只是展示如何旋转整个画布的文章和示例。现在,我猜我必须旋转画布,绘制图像,然后在绘制第二幅图像之前将画布旋转回其原始位置。如果是这样,那就让我知道吧!我只是觉得还有另一种方式。
Anyone have any idea?
任何人有任何想法?
Thanks in advance!
提前致谢!
回答by
I ran into the same problem in a recent project (where I kicked rotating aliens all over the place). I just used this humble function that does the same thing and can be used the same way as ctx.rotate but can be passed an angle. Works fine for me.
我在最近的一个项目中遇到了同样的问题(我把旋转的外星人踢到了所有地方)。我只是使用了这个不起眼的函数,它做同样的事情,可以像 ctx.rotate 一样使用,但可以传递一个角度。对我来说很好用。
function drawImageRot(img,x,y,width,height,deg){
// Store the current context state (i.e. rotation, translation etc..)
ctx.save()
//Convert degrees to radian
var rad = deg * Math.PI / 180;
//Set the origin to the center of the image
ctx.translate(x + width / 2, y + height / 2);
//Rotate the canvas around the origin
ctx.rotate(rad);
//draw the image
ctx.drawImage(img,width / 2 * (-1),height / 2 * (-1),width,height);
// Restore canvas state as saved from above
ctx.restore();
}
Yay, my first answer!
是的,我的第一个答案!
回答by Artiom Chilaru
Unfortunately in the HTML5 canvas element you can't rotate individual elements.
不幸的是,在 HTML5 画布元素中,您不能旋转单个元素。
Animation works like drawing in MS Paint: You draw something, make a screen.. use the eraser to remove some stuff, draw something differently, make a screen.. Draw something else on top, make a screen.. etc etc.
动画就像在 MS Paint 中绘图:你画一些东西,制作一个屏幕......使用橡皮擦去除一些东西,绘制不同的东西,制作一个屏幕......在上面绘制其他东西,制作一个屏幕......等等。
If you have an existing item on the canvas - you'll have to erase it ( use ctx.fillRect()or clearRect()for example ), and then draw the rotated object.
如果画布上有一个现有项目 - 您必须擦除它(例如使用ctx.fillRect()或clearRect()),然后绘制旋转的对象。
If you're not sure how to rotate it while drawing in the first place:
如果您不确定如何在绘图时旋转它:
ctx.save();
ctx.rotate(0.17);
// draw your object
ctx.restore();
回答by Anthony W
To rotate a individual object you have to set the transformation matrix. This is really simple:
要旋转单个对象,您必须设置变换矩阵。这真的很简单:
<body>
<canvas width="1280" height="720" id="pageCanvas">
You do not have a canvas enabled browser
</canvas>
<script>
var context = document.getElementById('pageCanvas').getContext('2d');
var angle = 0;
function convertToRadians(degree) {
return degree*(Math.PI/180);
}
function incrementAngle() {
angle++;
if(angle > 360) {
angle = 0;
}
}
function drawRandomlyColoredRectangle() {
// clear the drawing surface
context.clearRect(0,0,1280,720);
// you can also stroke a rect, the operations need to happen in order
incrementAngle();
context.save();
context.lineWidth = 10;
context.translate(200,200);
context.rotate(convertToRadians(angle));
// set the fill style
context.fillStyle = '#'+Math.floor(Math.random()*16777215).toString(16);
context.fillRect(-25,-25,50,50);
context.strokeRect(-25,-25,50,50);
context.restore();
}
// Ideally use getAnimationFrame but for simplicity:
setInterval(drawRandomlyColoredRectangle, 20);
</script>
</body>
回答by TTalt
Basically, to make an object rotate properly without having other shape rotating around, you need to:
基本上,要使对象正确旋转而没有其他形状旋转,您需要:
- save the context: ctx.save()
- move the pivot point to the desired location: ctx.translate(200, 200);
- rotate: context.rotate(45 * Math.PI / 180);
- draw the shape, sprite, whatever: ctx.draw...
- reset the pivot: ctx.translate(-200, -200);
- restore the context to its original state: ctx.restore();
- 保存上下文:ctx.save()
- 将枢轴点移动到所需位置: ctx.translate(200, 200);
- 旋转:context.rotate(45 * Math.PI / 180);
- 绘制形状,精灵,随便:ctx.draw ...
- 重置枢轴:ctx.translate(-200, -200);
- 将上下文恢复到原始状态:ctx.restore();
function spinDrawing() {
ctx.save();
ctx.translate(200, 200);
context.rotate(45 * Math.PI / 180);
ctx.draw //your drawing function
ctx.translate(-200, -200);
ctx.restore();
}
Caveats: After you translating , the origin of the canvas changed, which means when you drawing the shape, the coordinate of the shape should be aligned accordingly.
注意事项:翻译后,画布的原点发生了变化,这意味着在绘制形状时,形状的坐标应相应对齐。
Shapes drawn outside the list mentioned above won′t be affected. I hope it helps.
在上述列表之外绘制的形状不会受到影响。我希望它有帮助。
回答by turbopipp
This html/javascript code might shed some light on the matter:
这个 html/javascript 代码可能会说明这个问题:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="233" height="233" style="border:1px solid #d3d3d3;">
your browser does not support the canvas tag </canvas>
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var canvasWidth=233;
var canvasHeight=233;
var rectWidth=100;
var rectHeight=150;
var x=30;
var y=30;
var translateX= x+(rectWidth/2);
var translateY= y+(rectHeight/2);
ctx.fillRect(x,y,rectWidth,rectHeight);
ctx.translate(translateX,translateY);
ctx.rotate(5*Math.PI/64); /* just a random rotate number */
ctx.translate(-translateX,-translateY);
ctx.fillRect(x,y,rectWidth,rectHeight);
</script>
</body>
</html>
I find it helpful to see the math related to rotating, I hope this was helpful to you too.
我发现看到与旋转相关的数学很有帮助,我希望这对你也有帮助。
回答by PGB
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="450" style="border:1px solid #d3d3d3;">
</canvas>
<Button id = "right" onclick = "rotateRight()">Right</option>
<Button id = "left" onclick = "rotateLeft()">Left</option>
<script src = "zoom.js">
</script>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
createRect();
function rotateRight()
{
ctx.save();
ctx.clearRect(0,0,500,450);
ctx.translate(c.width/2,c.height/2);
ctx.rotate(10*Math.PI/180 );
ctx.translate(-c.width/2,-c.height/2);
createRect();
}
function rotateLeft()
{
ctx.save();
ctx.clearRect(0,0,500,450);
ctx.translate(c.width/2,c.height/2);
ctx.rotate(-10*Math.PI/180 );
ctx.translate(-c.width/2,-c.height/2);
createRect();
}
function createRect()
{
ctx.beginPath();
ctx.fillStyle = "#AAAA00";
ctx.fillRect(250,250,90,50);
}
</script>
</body>
</html>
回答by MichaelCalvin
To rotate an object you can use rotate()method. Here the example how to rotate a rectangular object to 135 degrees of clockwise.
要旋转对象,您可以使用rotate()方法。这是如何将矩形对象顺时针旋转 135 度的示例。
<script>
var canvas = document.getElementById('Canvas01');
var ctx = canvas.getContext('2d');
var rectWidth = 100;
var rectHeight = 50;
//create line
ctx.strokeStyle= '#ccc';
ctx.beginPath();
ctx.moveTo(canvas.width / 2, 0);
ctx.lineTo(canvas.width / 2, canvas.height);
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.moveTo(0, canvas.height/2);
ctx.lineTo(canvas.width, canvas.height/2);
ctx.stroke();
ctx.closePath();
// translate ctx to center of canvas
ctx.translate(canvas.width / 2, canvas.height / 2);
// rotate the rect to 135 degrees of clockwise
ctx.rotate((Math.PI / 180)*135);
ctx.fillStyle = 'blue';
ctx.fillRect(0, 0, rectWidth, rectHeight);
</script>
</body>
Here the demo and you can try yourself: http://okeschool.com/examples/canvas/html5-canvas-rotate
这是演示,您可以自己尝试: http://okeschool.com/examples/canvas/html5-canvas-rotate
回答by Alexander Bunting
I found this question because I had a bunch of stuff on a canvas, drawn with canvas lines, painstakingly, and then decided some of them should be rotated. Not wanting to do a whole bunch of complex stuff again I wanted to rotate what I had. A simple solution I found was this:
我发现这个问题是因为我在画布上有一堆东西,用画布线条绘制,煞费苦心,然后决定其中一些应该旋转。不想再做一大堆复杂的事情,我想轮换我拥有的东西。我发现一个简单的解决方案是这样的:
ctx.save();
ctx.translate(x+width_of_item/2,y+height_of_item/2);
ctx.rotate(degrees*(Math.PI/180));
ctx.translate(-(x+width_of_item/2),-(y+height_of_item/2));
// THIS IS THE STUFF YOU WANT ROTATED
// do whatever it is you need to do here, moveto and lineto is all i used
// I would expect anything to work. use normal grid coordinates as if its a
// normal 0,0 in the top left kind of grid
ctx.stroke();
ctx.restore();
Anyway - it might not be particularly elegant but its a dead easy way to rotate one particular element onto your canvas.
无论如何 - 它可能不是特别优雅,但它是将一个特定元素旋转到画布上的一种非常简单的方法。

