我有一个用于缩放图像以适合其内部的画布,我正在尝试的是以比画布设置的更大的尺寸导出图像。我使用canvas.toBlob方法获取blob数据,并将其作为上传文件发送到我的服务器。
例如,画布是350px乘350px,我想将图像保存为800px×1000px。
<canvas id="myCanvas" width="350" height="350"></canvas>
<script type="text/javasript">
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
var img_info = { width:527, height:350 };
var sourceX = 0;
var sourceY = 150;
var sourceWidth = 4520;
var sourceHeight = 3000;
var destWidth = img_info.width;
var destHeight = img_info.height;
var destX = canvas.width / 2 - destWidth / 2;
var destY = canvas.height / 2 - destHeight / 2;
context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
};
imageObj.src = 'hhttp://i.imgur.com/tKplLLb.jpg';
canvas.toBlob(
function (blob) {
var formData = new FormData();
formData.append('file', blob);
jQuery.ajax({
url: "test.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function (res) {
}
});
},
'image/jpg'
);
</script>
答案 0 :(得分:3)
此函数采用画布和宽度+高度参数。它将返回一个新的canvas元素,您可以在其上调用toBlob
function getResizedCanvas(canvas,newWidth,newHeight) {
var tmpCanvas = document.createElement('canvas');
tmpCanvas.width = newWidth;
tmpCanvas.height = newHeight;
var ctx = tmpCanvas.getContext('2d');
ctx.drawImage(canvas,0,0,canvas.width,canvas.height,0,0,newWidth,newHeight);
return tmpCanvas;
}
这里的工作示例:http://jsfiddle.net/L4dua/