Skip to content

Instantly share code, notes, and snippets.

@metaist
Last active August 29, 2015 14:11
Show Gist options
  • Save metaist/17152dd7929b38a28e0f to your computer and use it in GitHub Desktop.
Save metaist/17152dd7929b38a28e0f to your computer and use it in GitHub Desktop.
Canvas Demos
<!DOCTYPE html>
<html>
<head>
<style>
html, body { margin: 0; }
canvas {
position: absolute;
height: 100%;
width: 100%;
margin: 0;
}
</style>
</head>
<body>
<canvas></canvas>
<script>
var app = {};
app.init = function () {
app.canvas = document.getElementsByTagName('canvas')[0];
app.ctx = app.canvas.getContext('2d');
app.x = 0;
app.y = 0;
app.resize();
window.setInterval(app.fall, 100);
return app;
};
app.resize = function () {
var ctx = app.ctx;
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
return app;
};
app.draw = function () {
var ctx = app.ctx;
ctx.fillRect(0, 0, 50, 50);
return app;
};
app.fall = function () {
var ctx = app.ctx,
w = ctx.canvas.width,
h = ctx.canvas.height;
app.x = (w / 2) - 25;
app.y += 5;
if (app.y >= h) { app.y = 0; }
ctx.clearRect(0, 0, w, h);
ctx.translate(app.x, app.y);
app.draw();
ctx.translate(-app.x, -app.y);
return app;
};
window.onresize = app.resize;
app.init();
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>
html, body { margin: 0; }
canvas {
position: absolute;
height: 100%;
width: 100%;
margin: 0;
}
</style>
</head>
<body>
<canvas></canvas>
<script>
var TAU = Math.PI * 2,
app = {};
app.init = function () {
app.canvas = document.getElementsByTagName('canvas')[0];
app.ctx = app.canvas.getContext('2d');
app.resize();
window.setInterval(app.rotate, 100);
return app;
};
app.resize = function () {
var ctx = app.ctx;
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
return app;
};
app.draw = function () {
var ctx = app.ctx,
w = ctx.canvas.width,
h = ctx.canvas.height,
x = (w / 2) - 25,
y = (h / 2) - 25;
ctx.beginPath();
ctx.moveTo(x, y);
x += 50; y += 0;
ctx.lineTo(x, y);
x += 0; y += 50;
ctx.lineTo(x, y);
x -= 50; y -= 0;
ctx.lineTo(x, y);
ctx.fill();
return app;
};
app.rotate = function () {
var ctx = app.ctx,
w = ctx.canvas.width,
h = ctx.canvas.height;
ctx.clearRect(0, 0, w, h);
ctx.translate(w/2, h/2);
ctx.rotate(TAU / 360);
ctx.translate(-w/2, -h/2);
app.draw();
return app;
};
window.onresize = app.resize;
app.init();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment