我正在尝试使用canvas进行一些操作。首先,用户上传图像,如果图像过大,我需要将其缩小。该部分已经正常工作。最近,我们遇到了iPhone用户上传图像的问题。这些图像存在方向问题。我已经找出如何提取方向,但是当我在canvas中操作图像时会发生什么就成了我的问题。
这是我需要做的事情:获取图像,translate(),scale(),rotate(),translate() <- 将其恢复到原始位置,drawImage()。
当我这样做时,图像的某些部分会消失在深渊中。
我手动设置了方向,这样我就可以看到每个位置的外观,如果是纵向方向,我会翻转画布。
我尝试过save()和restore()。我尝试过translate(x,y)然后translate(-x,-y)。我的猜测是因为比例尺的缘故,网格偏离了,需要将x和y乘以比例尺。我尝试过使用scaleRatio进行计算,但仍然无效。
正如你所看到的,我手动设置了平移,但这只适用于我正在处理的图像大小,所以这不是一个好的解决方案!
以下是代码: JSFiddle 如果我正常旋转右侧,一切都正常。
谢谢!
这是我需要做的事情:获取图像,translate(),scale(),rotate(),translate() <- 将其恢复到原始位置,drawImage()。
当我这样做时,图像的某些部分会消失在深渊中。
if (dimensions[0] > 480 || dimensions[1] > 853) {
// Scale the image.
var horizontal = width > height;
if (horizontal) {
scaledHeight = 480;
scaleRatio = scaledHeight / height;
scaledWidth = width * scaleRatio;
} else {
scaledWidth = 640;
scaleRatio = scaledWidth / width;
scaledHeight = height * scaleRatio;
}
canvas['width'] = scaledWidth;
canvas['height'] = scaledHeight;
ctx['drawImage'](image, 0, 0, width, height, 0, 0, scaledWidth, scaledHeight);
/* Rotate Image */
orientation = 8; //manual orientation -> on the site we use loadImage to get the orientation
if(orientation != 1){
switch(orientation){
case 8:
case 6:
canvas.width = scaledHeight;
canvas.height = scaledWidth;
break;
}
var halfScaledWidth = scaledWidth/2;
var halfScaledheight = scaledHeight/2;
ctx.save(); //<- SAVE
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.translate(halfScaledWidth,halfScaledheight);
switch(orientation){
case 8: //rotate left
ctx.scale(scaleRatio,scaleRatio);
ctx.rotate(-90*Math.PI/180);
ctx.translate(-1380,-1055); // <-Manuial numbers
break;
case 3: //Flip upside down
ctx.scale(scaleRatio,scaleRatio);
ctx.rotate(180*Math.PI/180);
ctx.translate(-925,-595); //<-Manuial numbers
break;
case 6: //rotate right
ctx.scale(scaleRatio,scaleRatio);
ctx.rotate(90*Math.PI/180);
ctx.translate(-462,-130); //<-Manuial numbers
break;
}
//re-translate and draw image
//ctx.translate(-halfScaledWidth,-halfScaledheight);
ctx.drawImage(image,-halfScaledWidth, -halfScaledheight);
ctx.restore(); //<- RESTORE
}
/* Rotate Image */
}
我手动设置了方向,这样我就可以看到每个位置的外观,如果是纵向方向,我会翻转画布。
我尝试过save()和restore()。我尝试过translate(x,y)然后translate(-x,-y)。我的猜测是因为比例尺的缘故,网格偏离了,需要将x和y乘以比例尺。我尝试过使用scaleRatio进行计算,但仍然无效。
正如你所看到的,我手动设置了平移,但这只适用于我正在处理的图像大小,所以这不是一个好的解决方案!
以下是代码: JSFiddle 如果我正常旋转右侧,一切都正常。
谢谢!