1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[JavaScript] Canvas 間で画像を転送する

Posted at

1. 直接 drawImage() メソッド等を呼ぶ方法

drawImage() メソッド等は HTMLCanvasElement および OffscreenCanvas を直接扱うことができます。

const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');

const offscreenCanvas = new OffscreenCanvas(300, 150);

// ...

context.drawImage(offscreenCanvas, 0, 0);

参考「CanvasRenderingContext2D: drawImage() メソッド - Web API | MDN
参考「WebGLRenderingContext: texImage2D() method - Web APIs | MDN

2. ImageBitmap にする方法

他の Canvas の画像を転送することのみを目的とする場合や、同じ画像を頻繁に描画する場合は、ImageBitmap にすることで高速に描画できます。

参考「[JavaScript] ImageBitmap について - Qiita

const canvas = document.createElement('canvas');
const context = canvas.getContext('bitmaprenderer');

const offscreenCanvas = new OffscreenCanvas(300, 150);

// ...

const imageBitmap = await createImageBitmap(offscreenCanvas);

context.transferFromImageBitmap(imageBitmap);
const canvas = document.createElement('canvas');
const context = canvas.getContext('bitmaprenderer');

const offscreenCanvas = new OffscreenCanvas(300, 150);

// ...

const imageBitmap = offscreenCanvas.transferToImageBitmap();

context.transferFromImageBitmap(imageBitmap);
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');

const offscreenCanvas = new OffscreenCanvas(300, 150);

// ...

const imageBitmap = await createImageBitmap(offscreenCanvas);

context.drawImage(imageBitmap, 0, 0);
imageBitmap.close();
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');

const offscreenCanvas = new OffscreenCanvas(300, 150);

// ...

const imageBitmap = offscreenCanvas.transferToImageBitmap();

context.drawImage(imageBitmap, 0, 0);
imageBitmap.close();

参考「ImageBitmap - Web API | MDN
参考「createImageBitmap() - Web API | MDN
参考「OffscreenCanvas: transferToImageBitmap() method - Web APIs | MDN
参考「ImageBitmapRenderingContext: transferFromImageBitmap() method - Web APIs | MDN
参考「ImageBitmap.close() - Web API | MDN

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?