Skip to content

Instantly share code, notes, and snippets.

@victorfern91
Last active February 7, 2022 10:16
Show Gist options
  • Save victorfern91/7521b7523d6b974baa19fcaa1ca7d83a to your computer and use it in GitHub Desktop.
Save victorfern91/7521b7523d6b974baa19fcaa1ca7d83a to your computer and use it in GitHub Desktop.
Buffered canvas
class Canvas {
constructor(width = 400, height = 400, options = { appendCanvas: true }) {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
this.context = canvas.getContext('2d');
this.element = canvas;
if (options.appendCanvas) {
document.body.appendChild(canvas)
}
}
drawImage(...args) {
this.context.drawImage(...args);
}
drawCircle(...args) {
this.context.arc(...args);
}
drawSprite(sprite, x, y) {
this.drawImage(sprite.element, x, y, sprite.width, sprite.height);
}
}
export class BufferedCanvas extends Canvas {
constructor(width, height) {
super(width, height, { appendCanvas: false });
}
}
export default Canvas;
const bufferedCanvas = new BufferedCanvas(100, 100);
const nodeAtBufferedCanvas = bufferedCanvas.drawCircle(100, 75, 50, 0, 2 * Math.PI);
const canvas = new Canvas();
canvas.drawImage(nodeAtBufferedCanvas.element, 0, 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment