1
votes

I'm trying to scale a local image through Javascript like this:

function resizeImage(file, func){
    var canvas = document.createElement('canvas');
    var img = new Image();
    img.onload = function () {
        var factor = img.width/800;
        canvas.width = 800;
        canvas.height = img.height/factor;
        ctx = canvas.getContext('2d');
        ctx.scale(factor, factor);
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        func(canvas.toDataURL());
    }
    img.src = file.dataload; //file is an json-Object and dataload a dataURI
}

Somehow the data returned by canvas.toDataURL() is not resized in any way. I double checked that canvas.width and canvas.height are the correct computed sizes.

Any idea what goes wrong?

1

1 Answers

0
votes

Try removing the scale() method as it only affects what is being drawn to the canvas bitmap, not the bitmap itself (the drawImage() will in any case scale the image properly).

You need to scale the canvas using the width and height properties. These are basis for the dimension you get with toDataURL().

var factor = img.width/800;
var scale = 2;
canvas.width = 800 * scale; 
canvas.height = img.height/factor * scale;

If you need the canvas element to stay the same on screen apply CSS to it as well:

canvas.style.width = 800 + 'px'; 
canvas.style.height = img.height/factor + 'px';