qjs-nanovg

Canvas2D on qjsm

lib/canvas2d.js is a thin CanvasRenderingContext2D emulation built on the nanovg, glfw and dom modules. Import it for its side effects and scripts written for the browser Canvas API (getContext('2d'), requestAnimationFrame, drawImage) run mostly unmodified in a real GLFW window.

Usage

qjsm has no DOM and no requestAnimationFrame. canvas2d.js provides them: importing it opens a GLFW window with a NanoVG context behind it and exports a canvas element and a requestAnimationFrame to draw with.

import { canvas, requestAnimationFrame } from 'canvas2d.js';   // installed next to nanovg.so

const ctx = canvas.getContext('2d');

function loop(t) {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillRect(10, 10, 100, 100);
  requestAnimationFrame(loop);
}
requestAnimationFrame(loop);

The canvas is 800×600 by default; set canvas.width and canvas.height to change it. The other exports are window, document, Image, cancelAnimationFrame, registerFont and the context classes. Importing also defines window, document and requestAnimationFrame as globals, so code written for a browser runs unchanged, but new code is clearer with the named imports. cmake --install copies canvas2d.js into the same directory as nanovg.so.

Known gaps

It is a thin emulation, not a pixel-perfect one: