在画布中通过自己的中心旋转图像

Tab*_*nde 6 javascript jquery html5 canvas image-rotation

我有一个奇怪的问题,当我做旋转传递文字角度值(我获得由控制台打印的前一个角度,而不是变量)它完美的工作,但如果我运行代码传递像我的代码下面的变量,图像被描绘成"更多的顶部,更多的左"(抱歉我的英语不好)

function setImg(src,x,y,angle)
{
    var TO_RADIANS = Math.PI/180;
    var base_image = new Image();
    base_image.src = src
    base_image.onload = function () {
        console.log("-->->"+parseFloat(angle))
            ctx.save(); //saves the state of canvas
            ctx.translate(x+(base_image.width/2), y+(base_image.height/2)); //let's translate
            ctx.rotate(angle*TO_RADIANS); //increment the angle and rotate the image
            ctx.drawImage(base_image, -(base_image.width/2),-(base_image.height/2)); //draw the image ;)
            ctx.restore(); //restore the state of canvas
    };

}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Bli*_*n67 4

函数ctx.transformctx.rotatectx.scale和 的ctx.translate工作原理是创建一个新矩阵,然后将现有变换与该新矩阵相乘。

这意味着使用这些函数的结果将根据转换的当前状态而变化。

为了确保将变换应用于默认(单位)矩阵,请使用用ctx.setTransform(1, 0, 0, 1, 0, 0)新的默认矩阵替换现有矩阵的函数重置变换矩阵。

如果您在每组转换之前执行此操作,则无需使用保存和恢复来保持当前转换状态。