Skip to content

Commit

Permalink
Simplify drawing to canvas
Browse files Browse the repository at this point in the history
  • Loading branch information
coocos committed Nov 18, 2020
1 parent 6724f28 commit dd5eb8e
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 22 deletions.
33 changes: 19 additions & 14 deletions src/canvas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,32 @@ import { nodes, isLeaf, Node } from "./quadtree";
export function initializeCanvas() {
const canvas = document.getElementById("canvas") as HTMLCanvasElement;
const scale = window.devicePixelRatio;
canvas.width = window.innerWidth * scale;
canvas.height = window.innerHeight * scale;
canvas.width = Math.floor(window.innerWidth * scale);
canvas.height = Math.floor(window.innerHeight * scale);
const context = canvas.getContext("2d") as CanvasRenderingContext2D;
context.scale(scale, scale);

return {
canvas,
context,
draw: (tree: Node) => {
clear(context, canvas.width, canvas.height);
for (let node of nodes(tree)) {
drawNode(context, node);
drawPoints(context, node);
}
},
width: canvas.width / scale,
height: canvas.height / scale,
element: canvas,
};
}

export function clearCanvas(context: CanvasRenderingContext2D) {
function clear(
context: CanvasRenderingContext2D,
width: number,
height: number
) {
context.fillStyle = "#eee";
context.fillRect(0, 0, window.innerWidth, window.innerHeight);
context.fillRect(0, 0, width, height);
}

function drawNode(context: CanvasRenderingContext2D, node: Node) {
Expand All @@ -35,11 +48,3 @@ function drawPoints(context: CanvasRenderingContext2D, node: Node) {
}
}
}

export function draw(tree: Node, context: CanvasRenderingContext2D) {
clearCanvas(context);
for (let node of nodes(tree)) {
drawNode(context, node);
drawPoints(context, node);
}
}
15 changes: 7 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { insert, construct } from "./quadtree";
import { draw, initializeCanvas } from "./canvas";
import { initializeCanvas } from "./canvas";

const { canvas, context } = initializeCanvas();
const canvas = initializeCanvas();

const points = Array.from({ length: 256 }, () => {
return {
Expand All @@ -17,13 +17,12 @@ let tree = construct(points, {
height: canvas.height,
});

draw(tree, context);
canvas.addEventListener("click", (event) => {
const { left, top } = canvas.getBoundingClientRect();
canvas.draw(tree);
canvas.element.addEventListener("click", (event) => {
const point = {
x: event.clientX - left,
y: event.clientY - top,
x: event.clientX,
y: event.clientY,
};
tree = insert(tree, point);
draw(tree, context);
canvas.draw(tree);
});
4 changes: 4 additions & 0 deletions src/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,8 @@
}
body {
margin: 0;
}
#canvas {
width: 100vw;
height: 100vh;
}

0 comments on commit dd5eb8e

Please sign in to comment.