JSFiddle - React, Tailwind, and code Playground
by mhctoledo
HTML
<canvas id="queImg" crossOrigin="Anonymous" ></canvas>
<!-- <input type="file" name="imagen" id="imagen" /> -->
JavaScript
var myImage = new Image();
var thecanvas = document.getElementById("queImg");
var ctx = thecanvas.getContext("2d");
myImage.onload = function() {
//ctx.drawImage(myImage, 0, 0, myImage.width, myImage.height);
var width = myImage.naturalWidth;
var height = myImage.naturalHeight;
var quality = 80;
//document.write("Width:",width,"<br>");
//document.write("Height:",height,"<br>");
var maxWidth = 1024; // Max width for the image
var maxHeight = 1024; // Max height for the image
var ratio = 0; // Used for aspect ratio
// Check if the current width is larger than the max
if (width > maxWidth){
ratio = maxWidth / width; // get ratio for scaling image
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}
// Check if current height is larger than max
if (height > maxHeight){
ratio = maxHeight / height; // get ratio for scaling image
width = width * ratio; // Reset width to match scaled image
height = height * ratio; // Reset height to match scaled image
}
//document.write("Width:",width,"<br>");
//document.write("Height:",height,"<br>");
//var cvs = document.createElement('canvas');
thecanvas.width = width;
thecanvas.height = height;
var ctx2 = thecanvas.getContext("2d").drawImage(myImage, 0, 0, width, height);
var canvas = document.getElementById("queImg");
var imagen_reducida = canvas.toDataURL();
console.log(imagen_reducida);
}
myImage.src = "http://cocacolacontigo.es/HTML/img/valoraciones/5922c321cd266.jpg";
//var newImageData = ctx2.toDataURL("image/png");
//var result_image_obj = new Image();
//result_image_obj.src = newImageData;
//document.getElementById("nueva_imagen").src=result_image_obj;