WOAH! Is that OffscreenCanvas?

Sam Wray

Creative [Developer/Coder] / Digital Artist / Musician / Pixelated Polymath

(too many interests / identity crisis)

modV + { live : js }

<canvas></canvas>

(closing tag required)

CanvasRenderingContext2D

WebGLRenderingContext

WebGL2RenderingContext

ImageBitmapRenderingContext

(also popular, but less mature)

🎉 OffscreenCanvas 🎉

const worker = new Worker();
const canvas = document.querySelector('canvas');

const offscreenControl = canvas.transferControlToOffscreen();
// yep, that's the actual function name 🙃

worker.postMessage({
  type: 'canvas',
  payload: offscreenControl,
},
  // list the OffscreenCanvas as a transferrable
  [offscreenControl],
);

In the main thread...

🎉 OffscreenCanvas 🎉

let canvas = e.data.payload; // within onmessage
const context = canvas.getContext('2d');

const text = 'Hello from Offscreen!';

function render(delta) {
  // OffscreenCanvas brings rAF to Workers!
  requestAnimationFrame(render);
  
  const { width, height } = canvas;

  context.font = '30pt sans-serif';
  context.textAlign = 'center';
  context.fillStyle = `hsl(${delta / 40}, 80%, 50%)`;
  context.fillText(text, width / 2, height / 2);
}

requestAnimationFrame(render);

In the Worker thread...

Games

Video rendering/processing

Art

Live visual performances

Canvas

OffscreenCanvas

const image = new Image();
image.src = './cats.jpg';
image.onload = () => {
  context.drawImage(image, 0, 0);
};
// Main thread
const bitmap =
  await createImageBitmap(image);

worker.postMessage({
  type: 'image',
  payload: bitmap,
, [bitmap]);

// Worker (in onmessage)
// Grab your transferrable
const imageData = e.payload;

context.drawImage(imageData);

Image with OffSC

Canvas

OffscreenCanvas

const video = new Video();
video.src = './cats.ogv';
video.canplaythrough = () => {
  context.drawImage(video, 0, 0);
};
// Main thread
function videoRender() {
  requestAnimationFrame(videoRender);

  const bitmap =
    await createImageBitmap(video);
    
  worker.postMessage({
    type: 'frame',
    payload: bitmap,
  , [bitmap]);
}

// Worker (in onmessage)
// Grab your transferrable
const frameData = e.payload;

context.drawImage(frameData, 0, 0);

Video with OffSC

OffscreenCanvas in modV

Thanks!

Twitter: @_2xAA

Everything else: @2xAA

WOAH! Is that OffScreenCanvas?

By Sam Wray

WOAH! Is that OffScreenCanvas?

  • 461
Loading comments...

More from Sam Wray