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

rotate image by its own center in canvas

本文关键字:旋转 图像 自己的 布中按      更新时间:2023-09-26

我有一个奇怪的问题,当我通过文字角度值进行旋转时(我得到控制台打印的上一个角度,而不是变量),它运行得很好,但如果我运行的代码通过下面的代码这样的变量,图像会被绘制为"更上更左"(对不起我的英语不好)

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
    };
}

谢谢!

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

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

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

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