Javascript HTML5 画布 drawImage 与一个角度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3793397/
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
HTML5 canvas drawImage with at an angle
提问by Greg
I am experimenting with animation in <canvas>
and can't work out how to draw an image at an angle. The desired effect is a few images drawn as usual, with one image rotating slowly. (This image is not at the centre of the screen, if that makes any difference).
我正在尝试动画<canvas>
,但无法弄清楚如何以某个角度绘制图像。所需的效果是像往常一样绘制几张图像,其中一张图像缓慢旋转。(如果这有什么不同的话,此图像不在屏幕中央)。
回答by Jakub Wieczorek
You need to modify the transformation matrix before drawing the image that you want rotated.
在绘制要旋转的图像之前,您需要修改变换矩阵。
Assume image points to an HTMLImageElement object.
假设图像指向一个 HTMLImageElement 对象。
var x = canvas.width / 2;
var y = canvas.height / 2;
var width = image.width;
var height = image.height;
context.translate(x, y);
context.rotate(angleInRadians);
context.drawImage(image, -width / 2, -height / 2, width, height);
context.rotate(-angleInRadians);
context.translate(-x, -y);
The x, y coordinates is the center of the image on the canvas.
x, y 坐标是画布上图像的中心。
回答by Yaume
I have written a function (based on Jakub's answer) that allows user to paint an image in a X,Y position based on a custom rotation in a custom rotation point:
我编写了一个函数(基于 Jakub 的回答),它允许用户根据自定义旋转点中的自定义旋转在 X、Y 位置绘制图像:
function rotateAndPaintImage ( context, image, angleInRad , positionX, positionY, axisX, axisY ) {
context.translate( positionX, positionY );
context.rotate( angleInRad );
context.drawImage( image, -axisX, -axisY );
context.rotate( -angleInRad );
context.translate( -positionX, -positionY );
}
Then you can call it like this:
然后你可以这样称呼它:
var TO_RADIANS = Math.PI/180;
ctx = document.getElementById("canvasDiv").getContext("2d");
var imgSprite = new Image();
imgSprite.src = "img/sprite.png";
// rotate 45o image "imgSprite", based on its rotation axis located at x=20,y=30 and draw it on context "ctx" of the canvas on coordinates x=200,y=100
rotateAndPaintImage ( ctx, imgSprite, 45*TO_RADIANS, 200, 100, 20, 30 );
回答by PetrolHead
It is interesting that the first solution worked for so many people, it didn't give the result I needed. In the end I had to do this:
有趣的是,第一个解决方案对这么多人都有效,但没有给出我需要的结果。最后我不得不这样做:
ctx.save();
ctx.translate(positionX, positionY);
ctx.rotate(angle);
ctx.translate(-x,-y);
ctx.drawImage(image,0,0);
ctx.restore();
where (positionX, positionY)
is the coordinates on the canvas that I want the image to be located at and (x, y)
is the point on the image where I want the image to rotate.
(positionX, positionY)
我希望图像所在的画布上的坐标在哪里,以及(x, y)
我希望图像旋转的图像点。