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

最后都变了- 提交于 2019-12-12 01:43:53

问题


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;

回答1:


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


来源:https://stackoverflow.com/questions/23141596/kineticjs-how-do-i-downsize-a-png-jpg-image-in-kineticjs-maintaining-high-quali

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!