Resizing an image in an HTML5 canvas

后端 未结 18 3014
半阙折子戏
半阙折子戏 2020-11-22 03:37

I\'m trying to create a thumbnail image on the client side using javascript and a canvas element, but when I shrink the image down, it looks terrible. It looks as if it was

18条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 04:00

    i got this image by right clicking the canvas element in firefox and saving as.

    alt text

    var img = new Image();
    img.onload = function () {
        console.debug(this.width,this.height);
        var canvas = document.createElement('canvas'), ctx;
        canvas.width = 188;
        canvas.height = 150;
        document.body.appendChild(canvas);
        ctx = canvas.getContext('2d');
        ctx.drawImage(img,0,0,188,150);
    };
    img.src = 'original.jpg';
    

    so anyway, here is a 'fixed' version of your example:

    var img = new Image();
    // added cause it wasnt defined
    var canvas = document.createElement("canvas");
    document.body.appendChild(canvas);
    
    var ctx = canvas.getContext("2d");
    var canvasCopy = document.createElement("canvas");
    // adding it to the body
    
    document.body.appendChild(canvasCopy);
    
    var copyContext = canvasCopy.getContext("2d");
    
    img.onload = function()
    {
            var ratio = 1;
    
            // defining cause it wasnt
            var maxWidth = 188,
                maxHeight = 150;
    
            if(img.width > maxWidth)
                    ratio = maxWidth / img.width;
            else if(img.height > maxHeight)
                    ratio = maxHeight / img.height;
    
            canvasCopy.width = img.width;
            canvasCopy.height = img.height;
            copyContext.drawImage(img, 0, 0);
    
            canvas.width = img.width * ratio;
            canvas.height = img.height * ratio;
            // the line to change
            // ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);
            // the method signature you are using is for slicing
            ctx.drawImage(canvasCopy, 0, 0, canvas.width, canvas.height);
    };
    
    // changed for example
    img.src = 'original.jpg';
    

提交回复
热议问题