Resizing an image in an HTML5 canvas

后端 未结 18 2750
半阙折子戏
半阙折子戏 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条回答
  •  -上瘾入骨i
    2020-11-22 04:06

    If you're simply trying to resize an image, I'd recommend setting width and height of the image with CSS. Here's a quick example:

    .small-image {
        width: 100px;
        height: 100px;
    }
    

    Note that the height and width can also be set using JavaScript. Here's quick code sample:

    var img = document.getElement("my-image");
    img.style.width = 100 + "px";  // Make sure you add the "px" to the end,
    img.style.height = 100 + "px"; // otherwise you'll confuse IE
    

    Also, to ensure that the resized image looks good, add the following css rules to image selector:

    • -ms-interpolation-mode: bicubic: introduce in IE7
    • image-rendering: optimizeQuality: introduced in FireFox 3.6

    As far as I can tell, all browsers except IE using an bicubic algorithm to resize images by default, so your resized images should look good in Firefox and Chrome.

    If setting the css width and height doesn't work, you may want to play with a css transform:

    • -moz-transform: scale(sx[, sy])
    • -webkit-transform:scale(sx[, sy])

    If for whatever reason you need to use a canvas, please note that there are two ways an image can be resize: by resizing the canvas with css or by drawing the image at a smaller size.

    See this question for more details.

提交回复
热议问题