【问题标题】:How do i just rotate a image in Javascript?我如何在Javascript中旋转图像?
【发布时间】:2013-04-21 14:47:42
【问题描述】:

当我尝试旋转我绘制的图像时,我正在编写一个 Javascript 程序。我试图在谷歌上搜索以找到我的答案,但我得到的只是如何旋转整个画布。我正在寻找的是一种只旋转图像的方法(这样想。我想根据他行走的方向旋转一个战士)。我尝试了许多不同的代码,但都一样,旋转整个画布。

这是我使用的一个示例:

ctx.rotate(20*Math.PI/180); 

还有:

var angle = 0; //init angle
images[0].onload = function () {
    ctx.drawImage(images[0], 0, 0);
    setInterval(function () {
        ctx.save();
        ctx.clearRect(-ctx.canvas.width / 2, -ctx.canvas.height / 2, ctx.canvas.width, ctx.canvas.height);
        ctx.rotate(Math.PI / 180 * (angle += 10)); //rotating at 10 degrees interval..
        ctx.drawImage(images[0], 0, 0);
        ctx.translate(ctx.canvas.width / 2, ctx.canvas.height / 2);
        ctx.restore();
    }, 16);
}

请帮帮我

【问题讨论】:

标签: javascript image syntax rotation angle


【解决方案1】:

画布的旋转是如何创建相对于图像的旋转的一部分。
要使图像的可见位置保持不变且不移动,您必须先将其居中。
如果不使图像居中,您将只能获得旋转整个画布的视觉效果。
您必须进行一些数学运算才能使其围绕图像中心旋转。

ctx.save();
ctx.translate(x, y); /*X and Y of the image, center point of the image */
ctx.rotate((Math.PI / 180) * rotation); /*rotation is in degrees, so this converts it to rads */
ctx.drawImage(img, -(img.width/2), -(img.height/2)); /* Draw and center the image */
ctx.restore();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    • 2017-04-14
    相关资源
    最近更新 更多