Search code examples
javascripthtmlcanvaskineticjs

KineticJS: How do I downsize a PNG/JPG Image in KineticJS maintaining high Quality?


I want to downsize a PNG/JPG image in KineticJS without losing quality.

I did the following but it leads to very poor quality:

var stage = new Kinetic.Stage({
    container: 'container',
    width: 1000,
    height: 1000
});
var layer = new Kinetic.Layer();

var imageObj = new Image();
imageObj.onload = function () {
    var someImage = new Kinetic.Image({
        image: imageObj,
    });

    // add the shape to the layer
    layer.add(someImage);

    // add the layer to the stage
    stage.add(layer);

    someImage.scale({
        x: 500,
        y: 500
    });
    layer.draw();
};
imageObj.src = // some image;

Solution

  • You can get good results by down-scaling the image in increments.

    Here's a function that takes a source image (or canvas) and scales it down:

    function scaleImage(source,scaleFactor){
        var canvas=document.createElement("canvas");
        var ctx=canvas.getContext("2d");
        canvas.width=source.width*scaleFactor;
        canvas.height=source.height*scaleFactor;
        ctx.drawImage(source,0,0,source.width*scaleFactor,source.height*scaleFactor);
        return(canvas);
    }
    

    The scaleImage function could be used like this to downscale a very large image:

    A Demo: http://jsfiddle.net/m1erickson/zYLLe/

    var img=new Image();
    img.onload=start;
    img.src="hugeImage.png";
    function start(){
    
        // c1 is 0.50 the size of img
    
        var c1=scaleImage(img,0.50);
    
        // c2 is 0.50 the size of c1  (==25% of the original img)
    
        var c2=scaleImage(c1,0.50);
    
        // and then create a Kinetic.Image using c2 as a source
    
        image1 = new Kinetic.Image({
            x:10,
            y:10,
            image:c2,
            draggable: true
        });
        layer.add(image1);
        layer.draw();
    }