Files
MarchingCube2D/script.js
2023-08-01 18:58:42 +02:00

163 lines
3.8 KiB
JavaScript

/*
1 1
1 1 NOTHING
1 0
1 1 \
1 1
0 1 \
0 0
1 1 _
1 1 --
0 0
1 0
1 0 |
0 1 |
0 1
0 0
0 1 NOTHING
0 1
0 0 NOTHING
1 0
0 0 NOTHING
0 0
1 0 NOTHING
*/
class Point2D
{
constructor(x, y, isActive)
{
this.x = x;
this.y = y;
this.IsActive = isActive;
}
}
window.addEventListener("load", () => {
const canvas = document.getElementById("gridCanvas");
const ctx = canvas.getContext("2d");
// Canvas-Größe anpassen
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Punktabstand für das Grid
const spacing = 32;
let array = [];
array.push([0, 0, 0, 0, 0, 0, 0]);
array.push([0, 0, 0, 1, 0, 0, 0]);
array.push([0, 0, 0, 1, 0, 0, 0]);
array.push([0, 1, 0, 1, 0, 0, 0]);
function drawPoint(ctx, x, y, color = "#000", size = 1) {
ctx.fillStyle = color;
ctx.fillRect(x, y, size, size);
}
function drawAlgo(ctx, tl, tr, bl, br, color = "#000", size = 1)
{
ctx.fillStyle = color;
if(tl !== undefined && br !== undefined)
{
if(tl.IsActive && br.IsActive)
{
ctx.moveTo(tl.X, tl.Y);
ctx.lineTo(br.X, br.Y);
return;
}
}
if(tl !== undefined && tr !== undefined)
{
if(tl.IsActive && tr.IsActive)
{
ctx.moveTo(tl.X, tl.Y);
ctx.lineTo(tr.X, tr.Y);
return;
}
}
if(bl !== undefined && br !== undefined)
{
if(bl.IsActive && br.IsActive)
{
ctx.moveTo(bl.X, bl.Y);
ctx.lineTo(br.X, br.Y);
return;
}
}
}
function drawGrid(grid) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = "#888";
ctx.lineWidth = 1;
// Vertikale Linien zeichnen
//for (let x = spacing; x < canvas.width; x += spacing) {
// ctx.beginPath();
// ctx.moveTo(x, 0);
// ctx.lineTo(x, canvas.height);
// ctx.stroke();
//}
// Horizontale Linien zeichnen
//for (let y = spacing; y < canvas.height; y += spacing) {
// ctx.beginPath();
// ctx.moveTo(0, y);
// ctx.lineTo(canvas.width, y);
// ctx.stroke();
//}
// Punkte zeichnen
//for (let x = spacing; x < canvas.width; x += spacing) {
// for (let y = spacing; y < canvas.height; y += spacing) {
// drawPoint(ctx, x, y, "#000", 2);
// }
//}
for (let y2 = 0; y2 < array.length; y2 += 1)
{
for (let x2 = 0; x2 < array[y2].length; x2 += 1)
{
drawPoint(ctx, x2 * spacing, y2 * spacing, "#000", 2);
}
}
for (let y2 = 0; y2 < array.length; y2 += 1)
{
for (let x2 = 0; x2 < array[y2].length; x2 += 1)
{
var tl = new Point2D(x2 * spacing, y2 * spacing, array[y2][x2]);
var tr = new Point2D(x2 * spacing + spacing, y2 * spacing, array[y2][x2+1]);
var bl = new Point2D(x2 * spacing, y2 * spacing + spacing, array[y2+1][x2]);
var br = new Point2D(x2 * spacing + spacing, y2 * spacing + spacing, array[y2 + 1][x2+1]);
drawAlgo(ctx, tl, tr, bl, br,"#000", 2);
}
}
}
// Bei Größenänderungen des Fensters das Grid neu zeichnen
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
drawGrid();
});
// Grid beim Laden der Seite zeichnen
drawGrid(array);
});