There is an error in your code, as you take the image that is on the canvas without before drawing it?
var img2 = new Image();
img2.src = canvas.toDataURL("image/jpeg", 1.0);
//Exibe (desenha) a imagem na tela
ctx.drawImage(img, 0, 0, width, height);
The right thing would be:
//Exibe (desenha) a imagem na tela
ctx.drawImage(img, 0, 0, width, height);
var img2 = new Image();
img2.src = canvas.toDataURL("image/jpeg", 1.0);
With this you could already get the expected result but you really want to show your jpg image on canvas? if yes, the canvas would turn it into png again then the correct one would show it in the gift:
document.body.appendChild(img2);
This would cause if the user wanted to save the image, it would already be in jpg.
Test your edited code here:
var img = document.getElementById("preview");
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var MAX_WIDTH = 800;
var MAX_HEIGHT = 800;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
//Exibe (desenha) a imagem na tela
ctx.drawImage(img, 0, 0, width, height);
var img2 = new Image();
img2.src = canvas.toDataURL("image/jpeg", 1.0);
document.body.appendChild(img2);
console.log(img2);
<img crossOrigin="anonymous" id="preview" style="display:none;" src="https://lh3.googleusercontent.com/-zXZsjsGeYX0/UiuAEl31SDI/AAAAAAAABYI/g77Sb8-lzbY/w1109-h633-no/15-02-2013_internet.jpg">
<canvas id="canvas" style="background-size:contain;display:none;"></canvas>
I think you forgot to join jsFiddle...
– Sergio
nusss q mess...kk
– Douglas Lopes
For me it’s in jpeg.
– Lollipop
I have just hidden the image and left only the canvas, so just try to save it to see it saved in png http://jsfiddle.net/x4gvgnwn/3/
– Douglas Lopes
This is what you are looking for -> http://jsfiddle.net/x4gvgnwn/4/ ?
– Sergio
Sergio, right click on the image and try to save, you will see that in your script it also saves in png...
– Douglas Lopes