Skip to content

Instantly share code, notes, and snippets.

@alpaylan
Created May 16, 2024 22:11
Show Gist options
  • Save alpaylan/dc1210b171228a3f156ce65902797469 to your computer and use it in GitHub Desktop.
Save alpaylan/dc1210b171228a3f156ce65902797469 to your computer and use it in GitHub Desktop.
Infinite Canvas Example
<!DOCTYPE html>
<html>
<head>
<title>Infinity</title>
</head>
<body>
<div id="infinite"></div>
<button onclick="addElement()">Add Element</button>
<input id="zoom" type="range" min="10" max="200" value="100">
</body>
<style>
#infinite {
width: 1000px;
height: 500px;
background-color: #000;
}
</style>
<script>
const canvas = {
initial: {
topLeft: { x: 0, y: 0 },
bottomRight: { x: 1000, y: 500 },
zoom: 100,
elements: []
},
topLeft: { x: 0, y: 0 },
bottomRight: { x: 1000, y: 500 },
zoom: 100,
elements: []
};
function draw(canvas) {
document.getElementById('infinite').innerHTML = '';
canvas.elements.forEach(element => {
const div = document.createElement('div');
div.style.position = 'absolute';
// Position the element based on the zoom and the center
div.style.left = (element.position.x - canvas.topLeft.x) * (canvas.zoom / 100) + 'px';
div.style.top = (element.position.y - canvas.topLeft.y) * (canvas.zoom / 100) + 'px';
div.style.width = element.size.x * (canvas.zoom / 100) + 'px';
div.style.height = element.size.y * (canvas.zoom / 100) + 'px';
div.style.backgroundColor = element.color;
document.getElementById('infinite').appendChild(div);
});
}
const addElement = () => {
const randomPosition = {x : Math.random() * 800, y: Math.random() * 300 };
const randomSize = {x : Math.random() * 200, y: Math.random() * 200 };
const randomColor = '#' + Math.floor(Math.random()*16777215).toString(16);
canvas.elements.push({
position: randomPosition,
size: randomSize,
color: randomColor
});
draw(canvas);
}
document.addEventListener('scroll', (e) => {
e.preventDefault();
canvas.topLeft.x += window.scrollX;
canvas.topLeft.y += window.scrollY;
draw(canvas);
}
)
document.getElementById('zoom').addEventListener('input', (e) => {
canvas.zoom = e.target.value;
// Zoom out from the center based on the zoom
const center = {
x: (canvas.topLeft.x + canvas.bottomRight.x) / 2,
y: (canvas.topLeft.y + canvas.bottomRight.y) / 2
};
const width = (canvas.initial.bottomRight.x - canvas.initial.topLeft.x) * (100 / canvas.zoom);
const height = (canvas.initial.bottomRight.y - canvas.initial.topLeft.y) * (100 / canvas.zoom);
console.log(width, height);
canvas.topLeft.x = center.x - width / 2;
canvas.topLeft.y = center.y - height / 2;
canvas.bottomRight.x = center.x + width / 2;
canvas.bottomRight.y = center.y + height / 2;
console.log(canvas);
console.log(center);
draw(canvas);
});
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment