Reputation: 28
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.
Upvotes: 0
Views: 1030
Reputation: 137171
An HTMLCanvasElement
is part of the CanvasImageSource
mixin, meaning you can directly use it with drawImage()
:
const [canvas1, canvas2] = document.querySelectorAll("canvas");
const ctx1 = canvas1.getContext("2d");
const ctx2 = canvas2.getContext("2d");
ctx1.fillStyle = "green"
ctx1.fillRect(0, 0, 50, 50);
ctx2.fillStyle = "red"
ctx2.fillRect(0, 0, 50, 50);
// draw canvas1 at (60, 0), with a 2x scale
ctx2.drawImage(canvas1, 60, 0, 600, 300);
canvas { border: 1px solid }
<canvas></canvas>
<canvas></canvas>
Upvotes: 1
Reputation: 22070
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);
});
Upvotes: 3