From e53d88c991ee4a780b735117879ca6bef8605042 Mon Sep 17 00:00:00 2001 From: Ladd Hoffman Date: Fri, 21 Jun 2024 11:17:14 -0500 Subject: [PATCH] refactor: object --- draw.js | 27 ++++++++++++++++----------- test.html | 6 +++--- 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/draw.js b/draw.js index 7a3b28a..182d23e 100644 --- a/draw.js +++ b/draw.js @@ -96,16 +96,13 @@ class Drawing { return [x, y]; } - square(p) { + object(p, opts, fn) { let history = []; - let maxAge = 2500; - let dashLength = 5; + const maxAge = opts?.trace?.age ?? 0; + const dashLength = 5; let distance = 0; - let width = 10; - let height = 10; this.sequence.push(() => { const [x, y] = this.getPoint(p); - this.ctx.fillRect(...this.pixel([x - width / 2, y + height / 2]), width * this.scale, height * this.scale); let ds = 0; if (history.length) { const dx = x - history[history.length - 1].p[0]; @@ -130,16 +127,24 @@ class Drawing { } } this.ctx.stroke(); + fn(x, y); }) } - circle(p) { - const radius = 5; - this.sequence.push(() => { + square(p, opts) { + const size = opts?.size ?? 10; + this.object(p, opts, (x, y) => { + this.ctx.fillRect(...this.pixel([x - size / 2, y + size / 2]), size * this.scale, size * this.scale); + }); + } + + circle(p, opts) { + const radius = opts?.radius ?? 5; + this.object(p, opts, (x, y) => { this.ctx.beginPath(); - this.ctx.ellipse(...this.pixel(this.getPoint(p)), radius * this.scale, radius * this.scale, 0, 0, 2*Math.PI); + this.ctx.ellipse(...this.pixel([x, y]), radius * this.scale, radius * this.scale, 0, 0, 2*Math.PI); this.ctx.fill(); - }) + }); } definePoint(name, fn) { diff --git a/test.html b/test.html index 8660544..b6154a6 100644 --- a/test.html +++ b/test.html @@ -12,15 +12,15 @@ const d = new Drawing(); d.setStroke('black', 4); d.polyline([0, 100], [0, 0], [100, 0]); - d.definePoint('p1', () => d.oscillatingPoint([25, 100], [100, 100], 5000)); + d.definePoint('p1', () => d.oscillatingPoint([25, 50], [100, 100], 5000)); d.setStroke('red', 2); d.line([0, 0], 'p1'); - d.setFill('blue'); d.definePoint('p2', () => { const [x, y] = d.getPoint('p1'); return [x, y - d.oscillatingValue(10, 40, 5000 / 3, Math.PI / 2)]; }); - d.square('p2'); + d.setFill('blue'); + d.square('p2', {trace: {age: 5000}}); d.setFill('cyan'); d.circle('p1'); d.start();