HTML画布:缩放图像以适应而不拉伸? [英] HTML Canvas: Scaling image to fit without stretching?

查看:953
本文介绍了HTML画布:缩放图像以适应而不拉伸?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的代码在画布内绘制和缩放图像。问题是内部渲染的图像被拉伸以适应。

Im using the code below to draw and scale an image inside a canvas. The issue being that the image rendered inside is stretched to fit.

如果可能的话,我希望根据宽度进行缩放,但要保持其宽高比。

If possible, I would like it to be scaled based on width but to maintain its aspect ratio.

任何想法?

//IMAGE LOADER
var canvas = document.getElementById('image-canvas');
var canvas2 = document.getElementById('image-canvas2');
ctx = canvas.getContext('2d');
ctx2 = canvas2.getContext('2d');

// Trigger the imageLoader function when a file has been selected
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', imageLoader, false);

function imageLoader() {
    var reader = new FileReader();
    reader.onload = function(event) {
        img = new Image();
        img.onload = function(){
            ctx.drawImage(img,0,0,canvas.width, canvas.height);
            ctx2.drawImage(img,0,0,canvas.width, canvas.height);
        }
        img.src = reader.result;
    }
    reader.readAsDataURL(fileInput.files[0]);
}


推荐答案

你可以找出尺寸将图像添加到DOM中的图像。一旦知道比率,就可以缩放图像以适合画布。

You can figure out dimensions of the image by adding it to the DOM. Once you know the ratio, you can scale your image to fit within your canvas.

ratio = width / height;
width = height * ratio;
height = width / ratio;

无论图像是横向还是纵向,以下都应该有效。

The following should work whether an image is landscape or portrait.

var canvas = document.getElementById('image-canvas');
var canvas2 = document.getElementById('image-canvas2');
var ctx = canvas.getContext('2d');
document.getElementById('fileInput').addEventListener('change', imageLoader, false);

function imageLoader() {
    var reader = new FileReader();
    reader.onload = function(event) {
        var img = new Image();
        img.onload = function(){
            var ct = document.getElementById('measure'); 
            ct.appendChild(img);
            var wrh = img.width / img.height;
            var newWidth = canvas.width;
            var newHeight = newWidth / wrh;
            if (newHeight > canvas.height) {
                newHeight = canvas.height;
                newWidth = newHeight * wrh;
            }
            ct.removeChild(img);
            ctx.drawImage(img,0,0, newWidth , newHeight);
        }
        img.src = reader.result;
    }
    reader.readAsDataURL(fileInput.files[0]);
}

/* Add image to the DOM here so user can't see it */
#measure { position: absolute; left: -10000px; top: -100000px;}
canvas { border: 1px solid red; }

<canvas id="image-canvas" width="300" height="300"></canvas>
<input type="file" id="fileInput" />
<div id="measure"></div>

你可以在这里玩它

这篇关于HTML画布:缩放图像以适应而不拉伸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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