I have a canvas that scales an image to fit inside of it, what I'm trying to do is export the image in a larger size than what the canvas is set to. I am using the canvas.toBlob method to get the blob data and am sending that to my server as an uploaded file.
For example, the canvas is 350px by 350px, I'd like to save the image as 800px by 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>
This function takes a canvas and width+height parameters. It will return a new canvas element on which you can call 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;
}
Working example here: http://jsfiddle.net/L4dua/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With