var p = this.get(0);
p.angle = 90;
if (p.angle >= 0) {
var rotation = Math.PI * p.angle / 180;
} else {
var rotation = Math.PI * (360+p.angle) / 180;
}
var costheta = Math.cos(rotation);
var sintheta = Math.sin(rotation);
var canvas = document.createElement('canvas');
var onLoad = false;
if (!p.oImage) {
canvas.oImage = new Image();
canvas.oImage.src = p.src;
canvas.oImage.width = p.width;
canvas.oImage.height = p.height;
onLoad = true;
} else {
canvas.oImage = p.oImage;
}
canvas.style.width = canvas.width = Math.abs(costheta*canvas.oImage.width) + Math.abs(sintheta*canvas.oImage.height);
canvas.style.height = canvas.height = Math.abs(costheta*canvas.oImage.height) + Math.abs(sintheta*canvas.oImage.width);
var context = canvas.getContext('2d');
context.save();
if (rotation <= Math.PI/2) {
context.translate(sintheta*canvas.oImage.height,0);
} else if (rotation <= Math.PI) {
context.translate(canvas.width,-costheta*canvas.oImage.height);
} else if (rotation <= 1.5*Math.PI) {
context.translate(-costheta*canvas.oImage.width,canvas.height);
} else {
context.translate(0,-sintheta*canvas.oImage.width);
}
context.rotate(rotation);
if (onLoad) {
canvas.oImage.onload = function() {
context.drawImage(canvas.oImage, 0, 0, canvas.oImage.width, canvas.oImage.height);
context.restore();
};
} else {
context.drawImage(canvas.oImage, 0, 0, canvas.oImage.width, canvas.oImage.height);
context.restore();
}
我得到的是画布尺寸正确旋转(我的意思是,旧宽度变成新高度,反之亦然),但是图像旋转了180度而不是90度。
我不知道如何调试它。
UPDATED
我注意到奇怪的行为仅在图像src是http url时发生。如果图像src是blob,则代码运行正常。我需要将图像旋转90度,但图像旋转180度。这是我在网上找到的代码(一个jquery插件),使用的是:var p = this.get(0); p。角度= 90;如果(p.angle> = 0){...应该