Search code examples
javascripthtmlhtml5-canvas

Convert html5 <canvas> image to bitmap usable in drawImage


I want to save canvas image as a bitmap to be able to later use it in drawImage.

Goal is to be able to change (eg. resize) canvas and keep it's contents (eg. scaled - canvas is always a square).

I tried: var tmp = createImageBitmap(canvas) ctx.drawImage(tmp,0,0)

What I got was an error that said 'tmp' is not a bitmap.


Solution

  • createImageBitmap returns a Promise, so the result is asynchronous and you have to wait for it with await:

    const img = await createImageBitmap(canvas);
    ctx.drawImage(img, 0, 0);
    

    Or if you can't use await because you target ES5 then do it the old fashioned way:

    createImageBitmap(canvas).then(img => {
        ctx.drawImage(img, 0, 0);
    });