refactor: object

This commit is contained in:
Ladd Hoffman 2024-06-21 11:17:14 -05:00
parent 2a75359997
commit e53d88c991
2 changed files with 19 additions and 14 deletions

27
draw.js
View File

@ -96,16 +96,13 @@ class Drawing {
return [x, y]; return [x, y];
} }
square(p) { object(p, opts, fn) {
let history = []; let history = [];
let maxAge = 2500; const maxAge = opts?.trace?.age ?? 0;
let dashLength = 5; const dashLength = 5;
let distance = 0; let distance = 0;
let width = 10;
let height = 10;
this.sequence.push(() => { this.sequence.push(() => {
const [x, y] = this.getPoint(p); 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; let ds = 0;
if (history.length) { if (history.length) {
const dx = x - history[history.length - 1].p[0]; const dx = x - history[history.length - 1].p[0];
@ -130,16 +127,24 @@ class Drawing {
} }
} }
this.ctx.stroke(); this.ctx.stroke();
fn(x, y);
}) })
} }
circle(p) { square(p, opts) {
const radius = 5; const size = opts?.size ?? 10;
this.sequence.push(() => { 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.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(); this.ctx.fill();
}) });
} }
definePoint(name, fn) { definePoint(name, fn) {

View File

@ -12,15 +12,15 @@
const d = new Drawing(); const d = new Drawing();
d.setStroke('black', 4); d.setStroke('black', 4);
d.polyline([0, 100], [0, 0], [100, 0]); 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.setStroke('red', 2);
d.line([0, 0], 'p1'); d.line([0, 0], 'p1');
d.setFill('blue');
d.definePoint('p2', () => { d.definePoint('p2', () => {
const [x, y] = d.getPoint('p1'); const [x, y] = d.getPoint('p1');
return [x, y - d.oscillatingValue(10, 40, 5000 / 3, Math.PI / 2)]; 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.setFill('cyan');
d.circle('p1'); d.circle('p1');
d.start(); d.start();