Skip to content

Instantly share code, notes, and snippets.

@snoopdouglas
Last active August 2, 2016 08:03
Show Gist options
  • Save snoopdouglas/26ad40852d6caf5f9fc251407ff46968 to your computer and use it in GitHub Desktop.
Save snoopdouglas/26ad40852d6caf5f9fc251407ff46968 to your computer and use it in GitHub Desktop.
Render entire page using 2D canvas while keeping data visible to crawlers/screen readers
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.2/normalize.min.css" rel="stylesheet">
<link href="/z1.css" rel="stylesheet">
<title>Canvas</title>
</head>
<body>
<main>
<div data-k="test">Value</div>
</main>
<canvas>
</canvas>
<script src="/z0.js"></script>
</body>
</html>
const root = document.documentElement;
const canvas = document.querySelector("canvas");
const pageData = (() => {
const dataNode = document.querySelector("main");
const data = {};
const recurse = (parentNode, parentData) => {
const children = parentNode.children;
for(let i = 0; i < children.length; i++) {
const node = children[i];
if(node.children.length !== 0) {
parentData[node.dataset.k] = {};
recurse(node, parentData[node.dataset.k]);
}
else {
parentData[node.dataset.k] = node.innerHTML;
}
}
};
recurse(dataNode, data);
return data;
})();
const ctx = canvas.getContext("2d");
const screen = {
w: root.offsetWidth,
h: root.offsetHeight,
};
const render = () => {
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, screen.w, screen.h);
ctx.font = 'sans-serif';
ctx.fillStyle = 'white';
ctx.fillText(pageData.test, 0, 100);
};
const resize = () => {
canvas.width = screen.w;
canvas.height = screen.h;
render();
};
window.addEventListener("resize", resize);
resize();
render();
html, body {
width: 100%;
height: 100%;
}
main {
position: absolute;
bottom: 100%;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment