Skip to content

Instantly share code, notes, and snippets.

@sbrl
Last active January 30, 2018 22:57
Show Gist options
  • Save sbrl/f8b584a383116b38da29 to your computer and use it in GitHub Desktop.
Save sbrl/f8b584a383116b38da29 to your computer and use it in GitHub Desktop.
An ES6 template for a HTML5 canvas experiment. #template #html5-canvas
"use strict";
/**
* @template https://gist.github.com/sbrl/f8b584a383116b38da29
*/
class Renderer
{
constructor(canvas)
{
this.canvas = canvas;
this.context = canvas.getContext("2d");
this.trackWindowSize();
}
nextFrame()
{
this.update();
this.render(this.canvas, this.context);
requestAnimationFrame(this.nextFrame.bind(this));
}
update()
{
}
render(canvas, context)
{
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "red";
context.fillRect(10, 10, 100, 100);
}
/**
* Updates the canvas size to match the current viewport size.
*/
matchWindowSize() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
//this.render(this.canvas, this.context);
}
/**
* Makes the canvas size track the window size.
*/
trackWindowSize() {
this.matchWindowSize();
window.addEventListener("resize", this.matchWindowSize.bind(this));
}
}
window.addEventListener("load", function (event) {
var canvas = document.getElementById("canvas-main"),
renderer = new Renderer(canvas);
renderer.nextFrame();
window.renderer = renderer;
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>HTML5 Canvas Experiment</title>
<script src="renderer.js"></script>
<link href="theme.css" rel="stylesheet" />
</head>
<body>
<canvas id="canvas-main"></canvas>
</body>
</html>
html, body { font-size: 100%; }
body
{
font-family: sans-serif;
}
#canvas-main
{
position: absolute;
top: 0; left: 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment