如何通过减小高度和宽度将 5MB 图像渲染到 canvas

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

我正在使用 fabricjs 渲染图像,但我拥有的图像非常大,接近 5 MB 甚至更多。 例如,我有一个图像具有 2130*1800 (width*height) 和我的 canvas 宽度和高度,我可以在 max is 90% of window.width*90% of window.height.

我该怎么做?

这是 jsFiddle 示例: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);
}

基本上,您需要计算如果按 canvas 高度缩放图像,宽度是多少,如果按 canvas 宽度缩放图像,高度是多少,以及曾经更小,然后你按那个尺寸缩放。

要使图像适合 canvas,请使用最小适合比例。可能会导致 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.

要用图像维护方面(截断图像)填充 canvas,请使用最大比例。

// 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);

只用忽略宽高比的图像填充 canvas。

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

编辑:我忘了添加..

将 canvas 设置为图像比例,允许您在图像坐标系中的 canvas 上绘图。

// 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