Generates a blue circle on a canvas
by velo_ninja
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Multiple Shapes with One Class</title>
</head>
<body>
<button onclick="createShape('circle')">Circle</button>
<button onclick="createShape('rectangle')">Rectangle</button>
<button onclick="createShape('line')">Line</button>
<button onclick="createShape('triangle')">Triangle</button>
<button onclick="createShape('ellipse')">Ellipse</button>
<canvas id="shapeCanvas" width="500" height="400" style="border:1px solid #000;"></canvas>
<script>
// General-purpose shape class
class Element {
constructor(type, params) {
this.type = type;
this.params = params; // shape-specific data
}
toJSON() {
return {
type: this.type,
...this.params
};
}
}
// Renderer handles all shapes
class CanvasRenderer {
constructor(canvasId) {
this.canvas = document.getElementById(canvasId);
this.ctx = this.canvas.getContext('2d');
}
clear() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
render(shapeData) {
const ctx = this.ctx;
ctx.fillStyle = shapeData.color || 'black';
ctx.strokeStyle = shapeData.color || 'black';
switch (shapeData.type) {
case 'circle':
ctx.beginPath();
ctx.arc(shapeData.x, shapeData.y, shapeData.radius, 0, Math.PI * 2);
ctx.fill();
break;
case 'rectangle':
ctx.fillRect(shapeData.x, shapeData.y, shapeData.width, shapeData.height);
break;
case 'line':
ctx.beginPath();
ctx.moveTo(shapeData.x1, shapeData.y1);
ctx.lineTo(shapeData.x2, shapeData.y2);
ctx.stroke();
break;
case 'triangle':
ctx.beginPath();
ctx.moveTo(shapeData.x1, shapeData.y1);
ctx.lineTo(shapeData.x2, shapeData.y2);
...