make infinte canvas with dotted background using html js
- User
make infinte canvas with dotted background using html js
- Assistant
make infinte canvas with dotted background using html js
Creating an infinite canvas with a dotted background using HTML and JavaScript involves setting up an HTML canvas element, drawing a dotted pattern on it, and implementing functionality to allow panning and zooming, giving the effect of an infinite canvas. Here’s a simple implementation:
First, set up the basic structure of your HTML page with a canvas element:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Infinite Canvas with Dotted Background</title>
<style>
body, html {
margin: 0;
overflow: hidden;
height: 100%;
}
#infiniteCanvas {
display: block;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<canvas id="infiniteCanvas"></canvas>
<script src="script.js"></script>
</body>
</html>
Create a script.js file that handles the canvas setup, drawing the dotted background, and implementing infinite scrolling:
const canvas = document.getElementById('infiniteCanvas');
const ctx = canvas.getContext('2d');
// Adjust canvas to full window size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let offsetX = 0, offsetY = 0; // Track canvas origin offset
let startX, startY; // Starting x and y positions for dragging
canvas.onmousedown = (event) => {
startX = event.clientX - offsetX;
startY = event.clientY - offsetY;
canvas.onmousemove = onDrag;
};
canvas.onmouseup = () => {
canvas.onmousemove = null;
};
canvas.onmouseleave = () => {
canvas.onmousemove = null;
};
// Draw dotted pattern
function drawDottedBackground() {
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Set pattern dimensions
const dotSpacing = 20;
const dotSize = 2;
// Draw dots
for (let x = -dotSize; x < canvas.width + dotSize; x += dotSpacing) {
for (let y = -dotSize; y < canvas.height + dotSize; y += dotSpacing) {
ctx.beginPath();
ctx.arc(x + (offsetX % dotSpacing), y + (offsetY % dotSpacing), dotSize, 0, Math.PI * 2);
ctx.fillStyle = "#888";
ctx.fill();
}
}
}
// Handle the drag operation
function onDrag(event) {
offsetX = event.clientX - startX;
offsetY = event.clientY - startY;
drawDottedBackground();
}
// Initial draw call
drawDottedBackground();
mousedown, mouseup, and mouseleave events control the panning operation. When the mouse is down, the canvas begins to track mouse movements, simulating dragging.drawDottedBackground function draws dots in the background using arc to create circles. The offset is accounted for to simulate infinite scrolling.This setup provides a simple infinite canvas where users can pan around a dotted background. You can extend this by adding zoom functionality, more sophisticated patterns, or allowing additional drawing operations.