Bri*_*utt 4 html javascript canvas
我有一个可以缩放图像以适应其中的画布,我想要做的是以比画布设置的更大的尺寸导出图像。我正在使用 canvas.toBlob 方法来获取 blob 数据并将其作为上传文件发送到我的服务器。
例如,画布是 350 像素 x 350 像素,我想将图像保存为 800 像素 x 1000 像素。
<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>
Run Code Online (Sandbox Code Playgroud)
这个函数需要一个画布和宽度+高度参数。它将返回一个新的画布元素,您可以在其上调用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;
}
Run Code Online (Sandbox Code Playgroud)
这里的工作示例:http : //jsfiddle.net/L4dua/
| 归档时间: |
|
| 查看次数: |
5955 次 |
| 最近记录: |