40

我正在尝试使用动画,<canvas>但不知道如何以某个角度绘制图像。想要的效果是像往常一样绘制几张图像,其中一张图像缓慢旋转。(此图像不在屏幕中央,如果这有什么不同的话)。

4

3 回答 3

80

您需要在绘制要旋转的图像之前修改变换矩阵。

假设图像指向一个 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);

x, y 坐标是画布上图像的中心。

于 2010-09-25T10:48:22.307 回答
14

我编写了一个函数(基于 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 );
}

然后你可以这样称呼它:

var TO_RADIANS = Math.PI/180; 
ctx = document.getElementById("canvasDiv").getContext("2d");
var imgSprite = new Image();
imgSprite.src = "img/sprite.png";

// rotate 45º 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 );
于 2014-06-05T09:56:35.240 回答
14

有趣的是,第一个解决方案适用于这么多人,但它没有给出我需要的结果。最后我不得不这样做:

ctx.save();
ctx.translate(positionX, positionY);
ctx.rotate(angle);
ctx.translate(-x,-y);
ctx.drawImage(image,0,0);
ctx.restore();

(positionX, positionY)我希望图像位于画布上的坐标在哪里,并且(x, y)是图像上我希望图像旋转的点。

于 2017-10-24T23:48:01.037 回答