图像缩放在本地工作,但不是从服务器运行时

时间:2013-01-14 17:35:40

标签: javascript html5 canvas html5-canvas

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

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

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

0 个答案:

没有答案