How to render a 5MB image onto canvas by reducing height and width

杀马特。学长 韩版系。学妹 提交于 2019-11-28 13:01:48

问题


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 width and height ,that I can afford at max is 90% of window.width*90% of window.height.

How can I do that ?


回答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.




回答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


来源:https://stackoverflow.com/questions/33297517/how-to-render-a-5mb-image-onto-canvas-by-reducing-height-and-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!