通过javascript旋转图像



我正在尝试使用javascript旋转图像,这应该很简单,但我不知道如何在画布上绘制在特定坐标旋转的图像。以下是我发现并尝试使用的代码:

ctx.save();  
// Translate to the center point of our image  
ctx.translate(selectedImg.width * 0.5, selectedImg.height * 0.5);  
// Perform the rotation  
ctx.rotate( rotAngle * 0.01745 );  
// Translate back to the top left of our image  
ctx.translate(-selectedImg.width * 0.5, -selectedImg.height * 0.5);  
// Finally we draw the image  
ctx.drawImage(selectedImg, 0, 0);  
// And restore the context ready for the next loop  
ctx.restore();  

它只是旋转左上角的图像。我怎样才能把图像画成右下角?

如MSDN上所述。drawImage函数有三个签名。

void ctx.drawImage(image, dx, dy);
void ctx.drawImage(image, dx, dy, dWidth, dHeight);
void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

其中d代表目的地,s代表来源。

这里的解决方案应该是计算图像分辨率和画布分辨率,并确保将图像放在画布内,然后计算我们应该绘制图像的x、y轴。

ctx.save();
// Translate to the center point of our image  
ctx.translate(selectedImg.width * 0.5, selectedImg.height * 0.5);
// Perform the rotation  
ctx.rotate(rotAngle * 0.01745);
// Translate back to the top left of our image  
ctx.translate(-selectedImg.width * 0.5, -selectedImg.height * 0.5);
// Finally we calculate the destination and draw the image 
var selectedImgWidth  = selectedImg.width;
var selectedImgHeight = selectedImg.height;
var xOffset = selectedImgWidth < canvas.width ? (canvas.width - selectedImgWidth) : 0;
var yOffset = selectedImgHeight < canvas.height ? (canvas.height - selectedImgHeight) : 0;
ctx.drawImage(selectedImg, xOffset, yOffset);
// instead of ctx.drawImage(selectedImg, 0, 0);  
// And restore the context ready for the next loop  
ctx.restore();

我希望能解决你的问题。

编辑1:成功的目的地目标

此函数适用于我:

CanvasRenderingContext2D.prototype.drawImageRotated = function (img,x,y,angle)
{
this.save();  

var cposX = x + img.width / 2;
var cposY = y + img.height / 2;

this.translate(cposX,cposY); // move canvas center
this.rotate(degToRad(angle));
this.translate(-cposX,-cposY);

this.drawImage(img, x, y);

this.restore();

}

最新更新