There is an error in your code, how do you get the image on the canvas without first 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, why do you even want to display your jpg image on the canvas? if so, the canvas would turn it into png again then the correct one would be to show it in the gift:
document.body.appendChild(img2);
This would mean that 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"><canvasid="canvas" style="background-size:contain;display:none;"></canvas>