Skip to content Skip to sidebar Skip to footer

How To Render A 5MB Image Onto Canvas By Reducing Height And Width

I am using fabricjs to render images but the images that I have are very large near to 5 MB or even more. For example I have a image having 2130*1800 (width*height) and my canvas w

Solution 1:

Here is the jsFiddle example : https://jsfiddle.net/CanvasCode/7oghuwe2/3/

Javascript

var imageRatio = image1.width / image1.height;

var newHeight = canvas1.width / imageRatio;
var newWidth = canvas1.height * imageRatio;

var heightDiff = newHeight - canvas1.height;
var widthDiff = newWidth - canvas1.width;

if (widthDiff >= heightDiff) {
    context1.drawImage(image1, 0, 0, canvas1.width, canvas1.width / imageRatio);
} else {
    context1.drawImage(image1, 0, 0, canvas1.height * imageRatio, canvas1.height);
}

Basically you need to calculate what the width would be if you scaled the image by the canvas height and what the height would be if you scale the image by the canvas width, and which ever is smaller, then you scale by that dimension.


Solution 2:

To fit an image to the canvas use the min fitting scale. May result in some empty regions on the canvas.

// centre img on canvas ctx to fit
var scale = Math.min(ctx.canvas.width / img.width, ctx.canvas.height / img.height); // get the min scale to fit
var x = (ctx.canvas.width - (img.width * scale) ) / 2; // centre x
var y = (ctx.canvas.height - (img.height * scale) ) / 2; // centre y
ctx.drawImage(img, x, y, img.width * scale, img.height * scale); // draw scaled img onto the canvas.

To fill the canvas with an image mainting aspect (truncates the image) use the max scale.

// centre img on canvas ctx to fill canvas
var scale = Math.max(ctx.canvas.width / img.width, ctx.canvas.height / img.height); // get the max scale to fit
var x = (ctx.canvas.width - (img.width * scale) ) / 2;
var y = (ctx.canvas.height - (img.height * scale) ) / 2;
ctx.drawImage(img, x, y, img.width * scale, img.height * scale);

To just fill the canvas with the image ignoring aspect.

ctx.drawImage(img, x, y, ctx.canvas.width, ctx.canvas.height);

EDIT: I forgot to add..

To set the canvas to the image scale allowing you to draw on the canvas in the image coordinate system.

// use min to fit, use max to fill
var scale = Math.max(ctx.canvas.width / img.width, ctx.canvas.height / img.height);
var x = (ctx.canvas.width - (img.width * scale) ) / 2;
var y = (ctx.canvas.height - (img.height * scale) ) / 2;
ctx.setTransform(scale, 0, 0, scale, x, y); // set the canvas to the scaled image coordinate system
ctx.drawImage(img, 0, 0); //draw the image at 0 0 as it now fits/fills

Post a Comment for "How To Render A 5MB Image Onto Canvas By Reducing Height And Width"