2D图形编辑器的基础背景板

代码实现

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>design</title>
<style>
body {
text-align: center;
font-family: monospace;
}
canvas {
background-color: black;
}
</style>
</head>
<body>
<canvas id="asteroids" width = "800" height = "800"></canvas>
<script>
let canvas = document.getElementById('asteroids');
let ctx = canvas.getContext('2d');
drawGrid(ctx, 10, 100)
function drawGrid(ctx, minor, major, stroke, fill) {
minor = minor || 10;
major = major || minor * 5;
stroke = stroke || '#00FF00';
fill = fill || '#009900';
ctx.save();
ctx.strokeStyle = stroke;
ctx.fillStyle = fill;
let width = ctx.canvas.width;
let height = ctx.canvas.height;
for (let x = 0; x < width; x += minor) {
ctx.beginPath();
ctx.strokeStyle = '#00FF00';
ctx.moveTo(x, 0);
ctx.lineTo(x, height);
ctx.lineWidth = (x % major == 0) ? 0.5 : 0.25;
ctx.stroke();
if(x % major == 0 ) {
ctx.fillText(x, x, 10);
}
}
for (let y = 0; y < height; y += minor) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(width, y);
ctx.lineWidth = (y % major == 0) ? 0.5 : 0.25;
ctx.stroke();
if(y % major == 0 ) {
ctx.fillText(y, 0, y + 10);
}
}
}
</script>
</body>
</html>