0

我正在尝试在加载到浏览器时缩放图像。这是我正在使用的代码-

function importImage(e) {
    var canvas = document.getElementsByTagName('canvas')[0];
    var ctx = canvas.getContext('2d');
    var reader = new FileReader;

    reader.onload = function(event) {
        event.preventDefault();
        var img = new Image;
        img.src = event.target.result;

        img.onload = function() {

        width = img.width;
        height = img.height;        
        var scaleX, scaleY, scale;
        var scaledWidth, scaledHeight;
        scaleX = width / canvas.width;
        scaleY = height / canvas.height;
        scale = scaleX > scaleY ? scaleX : scaleY;
        scaledWidth = width / scale;
        scaledHeight = height / scale;
        ctx.clearRect(0,0, canvas.width, canvas.height);
        ctx.drawImage(img, (canvas.width - scaledWidth) / 2, (canvas.height - scaledHeight) / 2, scaledWidth, scaledHeight);       
        }
    }
    reader.readAsDataURL(e.target.files[0]);
}

从本地计算机使用时它似乎工作正常,但从服务器运行时,缩放不起作用。我认为这与我指的是实际图像有关,但我不确定。

4

0 回答 0