我有一个奇怪的问题,当我通过文字 Angular 值进行旋转时(我得到控制台打印的前一个 Angular 并代替变量)它工作得很好但是如果我运行传递变量的代码就像我下面的代码,图像被绘制为“更多的顶部和更多的左侧”(抱歉我的英语不好)
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.transform
、ctx.rotate
、ctx.scale
和 ctx.translate
起作用通过创建一个新矩阵,然后将现有变换与该新矩阵相乘。
这意味着使用这些函数的结果将根据转换的当前状态而变化。
为确保将转换应用于默认(身份)矩阵,使用函数 ctx.setTransform(1, 0, 0, 1, 0, 0)
重置转换矩阵,该函数替换了现有矩阵与新的默认矩阵。
如果您在每组转换之前执行此操作,则无需使用保存和恢复来保持当前转换状态。
关于javascript - 在 Canvas 中以自己的中心旋转图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34556621/