Rectangle 27 0

javascript Resizing an image in an HTML5 canvas?

-moz-transform: scale(sx[, sy])
-webkit-transform:scale(sx[, sy])
.small-image {
    width: 100px;
    height: 100px;
var img = document.getElement("my-image"); = 100 + "px";  // Make sure you add the "px" to the end, = 100 + "px"; // otherwise you'll confuse IE
  • -ms-interpolation-mode: bicubic: introduce in IE7
  • image-rendering: optimizeQuality: introduced in FireFox 3.6

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

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.

Chrome 27 produces nice resized image, but you can't copy the result to a canvas; attempting to do so will copy the original image instead.

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.

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

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:

Neither resizing the canvas nor drawing the image at a smaller size resolves the problem (in Chrome), sadly.

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

Rectangle 27 0

javascript Resizing an image in an HTML5 canvas?

$(document).on('ready', createImage);
$(window).on('resize', createImage);

var createImage = function(){
  var canvas = document.getElementById('myCanvas');
  canvas.width = window.innerWidth || $(window).width();
  canvas.height = window.innerHeight || $(window).height();
  var ctx = canvas.getContext('2d');
  img = new Image();
  img.addEventListener('load', function () {
    ctx.drawImage(this, 0, 0, w, h);
  img.src = '';
<script src=""></script>
    <meta charset="utf-8" />
    <title>Canvas Resize</title>
    <canvas id="myCanvas"></canvas>
html, body{
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  background: #000;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 0;

Also, sorry for using jQuery for simple selectors but I just feel too comfortable with the syntax.

Here is some code that resizes the image every time you reload the image. I am aware this is not optimal at all, but I provide it as a proof of concept.

I know this is an old thread but it might be useful for some people such as myself that months after are hitting this issue for the first time.

I tested it in Chrome 6 and Firefox 3.6, both on the Mac. This "technique" eats processor as it if was ice cream in the summer, but it does the trick.

My createImage function is called once when the document is loaded and after that it is called every time the window receives a resize event.

Rectangle 27 0

javascript Resizing an image in an HTML5 canvas?

I haven't added the lanczos stuff above, so feel free to add that as a comparison if you'd like.

These can be copy/pasted and can be used inside of web workers to resize images (or any other operation that requires interpolation - I'm using them to defish images at the moment).

Rectangle 27 0

javascript Resizing an image in an HTML5 canvas?

All resize principles were described very well in this thread, and pica does not add rocket science. But it's optimized very well for modern JIT-s, and is ready to use out of box (via npm or bower). Also, it use webworkers when available to avoid interface freezes.

For example, original image from first post is resized in 120ms with Lanczos filter and 3px window or 60ms with Box filter and 0.5px window. For huge 17mb image 5000x3000px resize takes ~1s on desktop and 3s on mobile.

I also plan to add unsharp mask support soon, because it's very useful after downscale.

Try pica - that's a highly optimized resizer with selectable algorythms. See demo.

Rectangle 27 0

javascript Resizing an image in an HTML5 canvas?

// returns a function that calculates lanczos weight
function lanczosCreate(lobes) {
    return function(x) {
        if (x > lobes)
            return 0;
        x *= Math.PI;
        if (Math.abs(x) < 1e-16)
            return 1;
        var xx = x / lobes;
        return Math.sin(x) * Math.sin(xx) / x / xx;

// elem: canvas element, img: image element, sx: scaled width, lobes: kernel radius
function thumbnailer(elem, img, sx, lobes) {
    this.canvas = elem;
    elem.width = img.width;
    elem.height = img.height; = "none";
    this.ctx = elem.getContext("2d");
    this.ctx.drawImage(img, 0, 0);
    this.img = img;
    this.src = this.ctx.getImageData(0, 0, img.width, img.height);
    this.dest = {
        width : sx,
        height : Math.round(img.height * sx / img.width),
    }; = new Array(this.dest.width * this.dest.height * 3);
    this.lanczos = lanczosCreate(lobes);
    this.ratio = img.width / sx;
    this.rcp_ratio = 2 / this.ratio;
    this.range2 = Math.ceil(this.ratio * lobes / 2);
    this.cacheLanc = {}; = {};
    this.icenter = {};
    setTimeout(this.process1, 0, this, 0);

thumbnailer.prototype.process1 = function(self, u) { = (u + 0.5) * self.ratio;
    self.icenter.x = Math.floor(;
    for (var v = 0; v < self.dest.height; v++) { = (v + 0.5) * self.ratio;
        self.icenter.y = Math.floor(;
        var a, r, g, b;
        a = r = g = b = 0;
        for (var i = self.icenter.x - self.range2; i <= self.icenter.x + self.range2; i++) {
            if (i < 0 || i >= self.src.width)
            var f_x = Math.floor(1000 * Math.abs(i -;
            if (!self.cacheLanc[f_x])
                self.cacheLanc[f_x] = {};
            for (var j = self.icenter.y - self.range2; j <= self.icenter.y + self.range2; j++) {
                if (j < 0 || j >= self.src.height)
                var f_y = Math.floor(1000 * Math.abs(j -;
                if (self.cacheLanc[f_x][f_y] == undefined)
                    self.cacheLanc[f_x][f_y] = self.lanczos(Math.sqrt(Math.pow(f_x * self.rcp_ratio, 2)
                            + Math.pow(f_y * self.rcp_ratio, 2)) / 1000);
                weight = self.cacheLanc[f_x][f_y];
                if (weight > 0) {
                    var idx = (j * self.src.width + i) * 4;
                    a += weight;
                    r += weight *[idx];
                    g += weight *[idx + 1];
                    b += weight *[idx + 2];
        var idx = (v * self.dest.width + u) * 3;[idx] = r / a;[idx + 1] = g / a;[idx + 2] = b / a;

    if (++u < self.dest.width)
        setTimeout(self.process1, 0, self, u);
        setTimeout(self.process2, 0, self);
thumbnailer.prototype.process2 = function(self) {
    self.canvas.width = self.dest.width;
    self.canvas.height = self.dest.height;
    self.ctx.drawImage(self.img, 0, 0, self.dest.width, self.dest.height);
    self.src = self.ctx.getImageData(0, 0, self.dest.width, self.dest.height);
    var idx, idx2;
    for (var i = 0; i < self.dest.width; i++) {
        for (var j = 0; j < self.dest.height; j++) {
            idx = (j * self.dest.width + i) * 3;
            idx2 = (j * self.dest.width + i) * 4;
  [idx2] =[idx];
  [idx2 + 1] =[idx + 1];
  [idx2 + 2] =[idx + 2];
    self.ctx.putImageData(self.src, 0, 0); = "block";
img.onload = function() {
    var canvas = document.createElement("canvas");
    new thumbnailer(canvas, img, 188, 3); //this produces lanczos3
    // but feel free to raise it up to 8. Your client will appreciate
    // that the program makes full use of his machine.

...with which you can produce results like these!

I had actually tried implementing it myself, doing as you did, copying code from an open source image editor. Since I wasn't able to find any solid documentation on the algorithm I had a hard time optimizing it. In the end, mine was kind of slow (took a few seconds to resize the image). When I get the chance, I'll try yours out and see if its any faster. And I think webworkers make multi-core javascript possible now. I was going to try using them to speed it up, but I was having trouble figuring out how to make this into a multithreaded algorithm

So what do you do if all the browsers (actually, Chrome 5 gave me quite good one) won't give you good enough resampling quality? You implement them yourself then! Oh come on, we're entering the new age of Web 3.0, HTML5 compliant browsers, super optimized JIT javascript compilers, multi-core() machines, with tons of memory, what are you afraid of? Hey, there's the word java in javascript, so that should guarantee the performance, right? Behold, the thumbnail generating code:

Sorry, forgot that! I've edited the reply. It's not going to be fast anyways, bicubic should be faster. Not to mention the algorithm I used is not the usual 2-way resizing (which is line by line, horizontal then vertical), so it's a looot slower.

This produces decent results, but takes 7.4 seconds for a 1.8 MP image in the latest version of Chrome...

You are awesome and deserve tons of awesomeage.

of course, you shouldn't use this code as it is in production app, because the thumbnailer object is never reused and thus will cause memory leak. Please think up of a proper destructor.

Rectangle 27 0

javascript Resizing an image in an HTML5 canvas?

function thumbnail(base64, maxWidth, maxHeight) {

  // Max size for thumbnail
  if(typeof(maxWidth) === 'undefined') var maxWidth = 500;
  if(typeof(maxHeight) === 'undefined') var maxHeight = 500;

  // Create and initialize two canvas
  var canvas = document.createElement("canvas");
  var ctx = canvas.getContext("2d");
  var canvasCopy = document.createElement("canvas");
  var copyContext = canvasCopy.getContext("2d");

  // Create original image
  var img = new Image();
  img.src = base64;

  // Determine new ratio based on max size
  var ratio = 1;
  if(img.width > maxWidth)
    ratio = maxWidth / img.width;
  else if(img.height > maxHeight)
    ratio = maxHeight / img.height;

  // Draw original image in second canvas
  canvasCopy.width = img.width;
  canvasCopy.height = img.height;
  copyContext.drawImage(img, 0, 0);

  // Copy and resize second canvas to first canvas
  canvas.width = img.width * ratio;
  canvas.height = img.height * ratio;
  ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);

  return canvas.toDataURL();


This is a javascript function adapted from @Telanor's code. When passing a image base64 as first argument to the function, it returns the base64 of the resized image. maxWidth and maxHeight are optional.

your approach is very fast but it produces a fuzzy image as you can see here:

Rectangle 27 0

javascript Resizing an image in an HTML5 canvas?

In addition, you may want to give SVG a shot, too, as it likely uses a different algorithm as well.

It should also be noted that canvas has different effects in different browsers (and even different versions of different browsers). The algorithms and techniques used in the browsers is likely to change over time (especially with Firefox 4 and Chrome 6 coming out so soon, which will place heavy emphasis on canvas rendering performance).

It'd be worth a shot to try drawing the image into a canvas control with the height and width attributes set to the size of the image and then using CSS to resize the canvas to the size you're looking for. Perhaps this would use a different resizing algorithm.

Setting the height & width of the canvas and resizing using CSS doesn't help, I've found (in Chrome). Even doing the resize using -webkit-transform rather than CSS width/height doesn't get the interpolation going.

Setting the width or height of a canvas via the HTML attributes causes the canvas to be cleared, so there cant be any resizing done with that method. Also, SVG is meant for dealing with mathematical images. I need to be able to draw PNGs and such, so that wont help me out there.

So something interesting that I found a while ago while working with canvas that might be helpful:

To resize the canvas control on its own, you need to use the height="" and width="" attributes (or canvas.width/canvas.height elements). If you use CSS to resize the canvas, it will actually stretch (i.e.: resize) the content of the canvas to fit the full canvas (rather than simply increasing or decreasing the area of the canvas.

Rectangle 27 0

javascript Resizing an image in an HTML5 canvas?

 * Hermite resize - fast image resize/resample using Hermite filter. 1 cpu version!
 * @param {HtmlElement} canvas
 * @param {int} width
 * @param {int} height
 * @param {boolean} resize_canvas if true, canvas will be resized. Optional.
function resample_single(canvas, width, height, resize_canvas) {
    var width_source = canvas.width;
    var height_source = canvas.height;
    width = Math.round(width);
    height = Math.round(height);

    var ratio_w = width_source / width;
    var ratio_h = height_source / height;
    var ratio_w_half = Math.ceil(ratio_w / 2);
    var ratio_h_half = Math.ceil(ratio_h / 2);

    var ctx = canvas.getContext("2d");
    var img = ctx.getImageData(0, 0, width_source, height_source);
    var img2 = ctx.createImageData(width, height);
    var data =;
    var data2 =;

    for (var j = 0; j < height; j++) {
        for (var i = 0; i < width; i++) {
            var x2 = (i + j * width) * 4;
            var weight = 0;
            var weights = 0;
            var weights_alpha = 0;
            var gx_r = 0;
            var gx_g = 0;
            var gx_b = 0;
            var gx_a = 0;
            var center_y = (j + 0.5) * ratio_h;
            var yy_start = Math.floor(j * ratio_h);
            var yy_stop = Math.ceil((j + 1) * ratio_h);
            for (var yy = yy_start; yy < yy_stop; yy++) {
                var dy = Math.abs(center_y - (yy + 0.5)) / ratio_h_half;
                var center_x = (i + 0.5) * ratio_w;
                var w0 = dy * dy; //pre-calc part of w
                var xx_start = Math.floor(i * ratio_w);
                var xx_stop = Math.ceil((i + 1) * ratio_w);
                for (var xx = xx_start; xx < xx_stop; xx++) {
                    var dx = Math.abs(center_x - (xx + 0.5)) / ratio_w_half;
                    var w = Math.sqrt(w0 + dx * dx);
                    if (w >= 1) {
                        //pixel too far
                    //hermite filter
                    weight = 2 * w * w * w - 3 * w * w + 1;
                    var pos_x = 4 * (xx + yy * width_source);
                    gx_a += weight * data[pos_x + 3];
                    weights_alpha += weight;
                    if (data[pos_x + 3] < 255)
                        weight = weight * data[pos_x + 3] / 250;
                    gx_r += weight * data[pos_x];
                    gx_g += weight * data[pos_x + 1];
                    gx_b += weight * data[pos_x + 2];
                    weights += weight;
            data2[x2] = gx_r / weights;
            data2[x2 + 1] = gx_g / weights;
            data2[x2 + 2] = gx_b / weights;
            data2[x2 + 3] = gx_a / weights_alpha;
    //clear and resize canvas
    if (resize_canvas === true) {
        canvas.width = width;
        canvas.height = height;
    } else {
        ctx.clearRect(0, 0, width_source, height_source);

    ctx.putImageData(img2, 0, 0);

@ViliusL Ah now I remembered why web workers didn't work so well. They didn't have shared memory before, and still doesn't have it now! Maybe someday when they manage to sort it out, your code will come to use (that, or maybe people use PNaCl instead)

Fast image resize/resample algorithm using Hermite filter with JavaScript. Support transparency, gives good quality. Preview:

Huge difference and decent performance. Thank you very much! before and after

Will you also share the webworkers version as well? Probably due to setup overhead, it's slower for small images, but it could be useful for larger source images.

added demo, git links, also multi-core version. Btw i did not spend too much time on optimizing multicore version... Single version i believe is optimized well.

Rectangle 27 0

javascript Resizing an image in an HTML5 canvas?

function resize_image( src, dst, type, quality ) {
     var tmp = new Image(),
         canvas, context, cW, cH;

     type = type || 'image/jpeg';
     quality = quality || 0.92;

     cW = src.naturalWidth;
     cH = src.naturalHeight;

     tmp.src = src.src;
     tmp.onload = function() {

        canvas = document.createElement( 'canvas' );

        cW /= 2;
        cH /= 2;

        if ( cW < src.width ) cW = src.width;
        if ( cH < src.height ) cH = src.height;

        canvas.width = cW;
        canvas.height = cH;
        context = canvas.getContext( '2d' );
        context.drawImage( tmp, 0, 0, cW, cH );

        dst.src = canvas.toDataURL( type, quality );

        if ( cW <= src.width || cH <= src.height )

        tmp.src = dst.src;

  // The images sent as parameters can be in the DOM or be image objects
  resize_image( $( '#original' )[0], $( '#smaller' )[0] );

works well when you are not resizing down more than half the original size

If you loop to only resize max one half at a time, the results would be quite good, and much faster than accessing pixel data.

The problem with some of this solutions is that they access directly the pixel data and loop through it to perform the downsampling. Depending on the size of the image this can be very resource intensive, and it would be better to use the browser's internal algorithms.

This function downsample to half at a time until reaching the desired size:

Rectangle 27 0

javascript Resizing an image in an HTML5 canvas?

var img = new Image();
// added cause it wasnt defined
var canvas = document.createElement("canvas");

var ctx = canvas.getContext("2d");
var canvasCopy = document.createElement("canvas");
// adding it to the body


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';
var img = new Image();
img.onload = function () {
    var canvas = document.createElement('canvas'), ctx;
    canvas.width = 188;
    canvas.height = 150;
    ctx = canvas.getContext('2d');
img.src = 'original.jpg';

I've tried doing what you did and its not coming out nice like yours. Unless I missed something, the only change you made was to use the scaling method signature instead of the slicing one, right? For some reason its not working for me.

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