Skip to content

Instantly share code, notes, and snippets.

@greggman
Last active April 3, 2024 23:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greggman/84d5875702cebeefb7a79f1a4c5fdd05 to your computer and use it in GitHub Desktop.
Save greggman/84d5875702cebeefb7a79f1a4c5fdd05 to your computer and use it in GitHub Desktop.
Canvas Background
body { margin: 0; }
canvas { position: fixed; width: 100vw; height: 100vh; }
.content { margin: 5px; }
<canvas></canvas>
<div class="content">
<p>the rest of the page goes here</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam rhoncus fermentum ullamcorper. Nulla vitae mauris mattis, pharetra metus vitae, pharetra lectus. Nam luctus imperdiet orci, eget consectetur diam bibendum vel. Ut sit amet consectetur lacus. Sed cursus felis at dignissim fringilla. Duis tristique efficitur sapien et sagittis. Aenean a nisl eget tellus posuere eleifend.
</p>
</div>
<script>
// tell the embed parent frame the height of the content
if (window.parent && window.parent.parent){
window.parent.parent.postMessage(["resultsFrame", {
height: document.body.getBoundingClientRect().height,
slug: "g8dayhdy"
}], "*")
}
// always overwrite window.name, in case users try to set it manually
window.name = "result"
</script>
(function() {
var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");
var history = [];
var maxHistory = 50;
var historyNdx = 0;
function render(time) {
time *= 0.001;
resizeCanvasToDisplaySize(canvas);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
var hw = canvas.width / 2;
var hh = canvas.height / 2;
ctx.translate(hw, hh);
ctx.beginPath();
for (var ii = 0; ii < 40; ++ii) {
var tm = time + ii * 0.05;
ctx.moveTo(Math.sin(tm) * hw, Math.sin(tm * 0.9 + 1.7) * hh);
ctx.lineTo(Math.sin(tm * 1.1 + 10.7) * hw, Math.sin(tm * 0.7 + 12.7) * hh);
}
ctx.strokeStyle = "red"
ctx.stroke();
ctx.restore();
if (history.length) {
ctx.strokeStyle = "blue";
ctx.beginPath();
var ndx = (historyNdx + history.length - 1) % history.length;
ctx.moveTo(history[ndx][0], history[ndx][1]);
for (var ii = 1; ii < history.length; ++ii) {
ndx = (ndx + history.length - 1) % history.length;
ctx.lineTo(history[ndx][0], history[ndx][1]);
}
ctx.stroke();
}
requestAnimationFrame(render);
}
requestAnimationFrame(render);
function resizeCanvasToDisplaySize(canvas) {
var width = canvas.clientWidth;
var height = canvas.clientHeight;
if (width != canvas.width || height != canvas.height) {
canvas.width = width;
canvas.height = height;
}
}
canvas.addEventListener('mousemove', function(e) {
history[historyNdx] = [e.clientX, e.clientY];
historyNdx = (historyNdx + 1) % maxHistory;
});
})();
{"name":"Canvas Background","settings":{},"filenames":["index.html","index.css","index.js"]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment