Search code examples
imagehtmlcanvasresizegetimagedata

HTML5 canvas - Rescale images on load?


Ok, so I'm doing an html5 canvas game, and I need to draw resized images all the time (it's all pixel-art). Unfortunately, doing the resizing on drawImage makes current browsers quite sluggish, so I'm trying to do the resizing on load, and then just draw the pre-resized image.

I've tried to draw the resized images to a hidden context and then do a ctx.getImageData, but then I'm stuck with a byte array and there's no way to convert to an image. I can do a putImageData to push it to the final context, but that's slow and I apparently lose the alpha channel.

Another option could be to pre-scale things in the server, but I'd like to avoid that if at all possible.

Any ideas?


Solution

  • There is a method on the canvas object (not the context) called toDataURL(string mimeType), this will convert the canvas contents to a base64-encoded binary string of an image. You can use this as the src attribute of any image element.

    ctx.drawImage(originalImage, 0, 0, originalImage.width, originalImage.height, 0, 0, 200, 200);
    var scaledImage = new Image();
    scaledImage.onload = ...;
    scaledImage.src = canvas.toDataURL("image/png");
    

    Now you can draw your scaled image normaly.