HTML Canvas:缩放图像以适应而不拉伸?

时间:2015-01-20 14:28:40

标签: javascript html5 canvas

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

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

有什么想法吗?

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

1 个答案:

答案 0 :(得分:15)

您可以通过将图像添加到DOM来确定图像的尺寸。一旦知道比率,就可以缩放图像以适合画布。

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

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



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>
&#13;
&#13;
&#13;

你可以play with it here