如何通过减小高度和宽度将5MB图像渲染到画布上 [英] How to render a 5MB image onto canvas by reducing height and width

查看:108
本文介绍了如何通过减小高度和宽度将5MB图像渲染到画布上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用fabricjs来渲染图像,但我拥有的图像非常大,接近5 MB甚至更多。
例如,我有一个图像 2130 * 1800(width * height)和我的画布宽度和高度,我可以在 window.height window.width * 90%的最大值为90% / p>

我如何做到这一点?

解决方案

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

基本上你需要计算如果你缩放图像画布高度以及如果您按照画布宽度缩放图片的高度,以及哪个更小,那么您将按照该维度缩放。


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 ?

解决方案

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.

这篇关于如何通过减小高度和宽度将5MB图像渲染到画布上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆