Adjust Image Inside A Canvas
Resize image within canvas when generating it. I'm trying to generate an image. From an image I convert it to a dataImage, and later I encode it to an image. and then put it inside
Solution 1:
You need to wait for the image to load before you can modify it. When you render it you must render it at the size you want. The drawImage
function has several versions one of which is ctx.drawImage(image,x,y,width,height)
which will draw the image at x
,y
and with a size as width
,height
.
const canvas = document.getElementById("result");
const ctx = canvas.getContext('2d');
const width = 300;
const height = 311;
const image = new Image;
image.src = 'http://tosemdinheiro.com/wp-content/uploads/2012/10/carro.jpg';
image.onload = function(){ // wait for the image to load
ctx.canvas.width = width; // set size
ctx.canvas.height = height;
ctx.drawImage(image,0,0,width,height); // draw the image at size
// Dont know why you are doing the following so removed it
//const imageData = res_ctx.getImageData(0, 0, width, height);
// create new image
const imageGif = new Image;
imageGif.src = canvas.toDataURL(); // "image/png" is the default mime type
document.querySelector(".frames").appendChild(imageGif);
}
Post a Comment for "Adjust Image Inside A Canvas"