Compare commits

...

25 Commits
0.0.6 ... main

Author SHA1 Message Date
69ab471d22 module exports 2023-11-05 02:04:18 -07:00
ea311a1787 improved init function 2023-11-05 01:21:01 -07:00
da77aa10bb Fixes circular SAT 2023-11-05 01:41:21 -06:00
e70787260a Refactors options and adds a fillScreen mode 2023-11-04 23:41:39 -06:00
31596774df Merge branch 'collision' 2023-11-04 13:16:11 -06:00
79e7996d46 sprite and gif animations 2023-11-04 13:06:49 -06:00
2e039719f6 animated sprites 2023-11-03 23:10:45 -06:00
c6c4b46312 refactors SAT to be less wet, adds spline and spline collision using SAT 2023-11-03 22:28:44 -06:00
9d8a0fc7d2 sat circle collision 2023-11-03 05:46:50 -06:00
62b13e49e7 changes hitbox getters to get properties, adds aaContains 2023-11-03 05:12:19 -06:00
601bc51233 Three types of collision and a polygon class 2023-11-03 04:51:50 -06:00
a7e7cd139f moveOrigin for zoomabledoodler 2023-10-28 07:38:29 -06:00
0959386ec2 adds drawWithOutline 2023-10-26 02:27:12 -06:00
65a34f960c post init 2023-10-26 01:17:59 -06:00
95afbf9bd3 drawWithAlpha 2023-10-25 17:40:39 -06:00
c58861bc93 deferred drawing 2023-10-24 01:11:15 -06:00
7d6b54825d oops 2023-10-24 00:55:01 -06:00
f1bd085384 text align 2023-10-24 00:49:49 -06:00
6661936188 clearing 2023-10-23 14:09:18 -06:00
e4de886646 text drawing 2023-10-23 04:35:03 -06:00
Emma
76f07625dd maxScale 2023-02-15 18:14:49 -07:00
Emma
3bf0c4587c Scaled drawing 2023-02-15 17:57:03 -07:00
Emma
c767c09776 Zoomable Canvas 2023-02-15 17:46:41 -07:00
Emma
fbcffcde27 fixed 2023-02-12 20:03:06 -07:00
Emma
c7ff737690 On Drag event 2023-02-12 19:57:12 -07:00
24 changed files with 3439 additions and 245 deletions

41
.vscode/settings.json vendored
View File

@ -1,24 +1,41 @@
{
"workbench.colorCustomizations": {
"activityBar.activeBackground": "#d816d8",
"activityBar.background": "#d816d8",
"activityBar.activeBackground": "#2f7c47",
"activityBar.background": "#2f7c47",
"activityBar.foreground": "#e7e7e7",
"activityBar.inactiveForeground": "#e7e7e799",
"activityBarBadge.background": "#caca15",
"activityBarBadge.foreground": "#15202b",
"activityBarBadge.background": "#422c74",
"activityBarBadge.foreground": "#e7e7e7",
"commandCenter.border": "#e7e7e799",
"sash.hoverBorder": "#d816d8",
"statusBar.background": "#aa11aa",
"sash.hoverBorder": "#2f7c47",
"statusBar.background": "#215732",
"statusBar.foreground": "#e7e7e7",
"statusBarItem.hoverBackground": "#d816d8",
"statusBarItem.remoteBackground": "#aa11aa",
"statusBarItem.hoverBackground": "#2f7c47",
"statusBarItem.remoteBackground": "#215732",
"statusBarItem.remoteForeground": "#e7e7e7",
"titleBar.activeBackground": "#aa11aa",
"titleBar.activeBackground": "#215732",
"titleBar.activeForeground": "#e7e7e7",
"titleBar.inactiveBackground": "#aa11aa99",
"titleBar.inactiveBackground": "#21573299",
"titleBar.inactiveForeground": "#e7e7e799"
},
"peacock.remoteColor": "aa11aa",
"peacock.remoteColor": "#215732",
"deno.enable": true,
"deno.unstable": true
"deno.unstable": true,
"liveServer.settings.port": 5501,
"cSpell.words": [
"BGRA",
"blitting",
"dpng",
"idat",
"iend",
"ihdr",
"imgscr",
"Namee",
"NMAX",
"omggif's",
"plte",
"trns",
"aabb",
"deadzone"
]
}

63
animation/gif.ts Normal file
View File

@ -0,0 +1,63 @@
import { Vector } from "../geometry/vector.ts";
import { Frame, handleGIF } from "../processing/gif.ts";
type frame = { canvas: HTMLCanvasElement } & Frame;
export class GIFAnimation {
frames: frame[] = [];
canvas: HTMLCanvasElement;
ctx!: CanvasRenderingContext2D;
ready = false;
constructor(
url: string,
private origin: Vector,
private scale = 1,
) {
this.canvas = document.createElement("canvas");
this.init(url);
}
async init(url: string) {
const res = await fetch(url);
const buf = new Uint8Array(await res.arrayBuffer());
const gif = handleGIF(buf);
this.frames = gif.frames;
this.frameTimes = this.frames.map((f) => f.delay);
this.totalAnimationTime = this.frameTimes.reduce(
(a, b) => a + b,
0,
);
this.canvas.width = gif.w;
this.canvas.height = gif.h;
this.ctx = this.canvas.getContext("2d")!;
this.ready = true;
}
frameTimes!: number[];
totalAnimationTime = 0;
_frameCounter = 0;
currentFrameIndex = 0;
draw(timeSinceLastFrame: number) {
if (!this.ready) return;
this._frameCounter += timeSinceLastFrame;
const currentFrameDelay = this.frames[this.currentFrameIndex].delay * 10;
while (this._frameCounter >= currentFrameDelay) {
this._frameCounter -= currentFrameDelay;
this.currentFrameIndex = (this.currentFrameIndex + 1) %
this.frames.length;
}
const currentFrame = this.frames[this.currentFrameIndex];
doodler.drawImage(
currentFrame.canvas,
this.origin,
this.canvas.width * this.scale,
this.canvas.height * this.scale,
);
}
}

45
animation/sprite.ts Normal file
View File

@ -0,0 +1,45 @@
import { Vector } from "../geometry/vector.ts";
export class SpriteAnimation {
image: HTMLImageElement;
origin: Vector;
constructor(
private imageUrl: string,
private cellWidth: number,
private cellHeight: number,
private cellCountX: number,
private cellCountY: number,
public timing = 1,
public scale = 1,
) {
this.image = new Image();
this.image.src = this.imageUrl;
this.origin = new Vector();
}
private _frameCount = 0;
private get frameCount() {
return this._frameCount += this.timing;
}
getCell() {
const time = Math.floor(this.frameCount);
const x = (time % this.cellCountX) * this.cellWidth;
const y = (Math.floor(time / this.cellCountX) % this.cellCountY) *
this.cellHeight;
return { x, y };
}
draw() {
const { x, y } = this.getCell();
doodler.drawSprite(
this.image,
new Vector(x, y),
this.cellWidth,
this.cellHeight,
this.origin,
this.cellWidth * this.scale,
this.cellHeight * this.scale,
);
}
}

1290
bundle.js

File diff suppressed because it is too large Load Diff

347
canvas.ts
View File

@ -1,33 +1,23 @@
/// <reference types="./global.d.ts" />
import { Constants } from "./geometry/constants.ts";
import { Vector } from "./geometry/vector.ts";
import { DoodlerOptions, postInit } from "./init.ts";
export const init = (opt: IDoodlerOptions) => {
if (window.doodler) throw 'Doodler has already been initialized in this window'
window.doodler = new Doodler(opt);
window.doodler.init();
}
interface IDoodlerOptions {
width: number;
height: number;
canvas?: HTMLCanvasElement;
bg?: string;
framerate?: number;
}
type layer = (ctx: CanvasRenderingContext2D, index: number) => void;
type layer = (
ctx: CanvasRenderingContext2D,
index: number,
frameTime: number,
) => void;
export class Doodler {
private ctx: CanvasRenderingContext2D;
private _canvas: HTMLCanvasElement;
protected ctx: CanvasRenderingContext2D;
protected _canvas: HTMLCanvasElement;
private layers: layer[] = [];
private bg: string;
private framerate: number;
protected bg: string;
private framerate?: number;
get width() {
return this.ctx.canvas.width;
@ -39,62 +29,87 @@ export class Doodler {
private draggables: Draggable[] = [];
private clickables: Clickable[] = [];
protected dragTarget?: Draggable;
constructor({
width,
height,
fillScreen,
canvas,
bg,
framerate
}: IDoodlerOptions) {
framerate,
}: DoodlerOptions, postInit?: postInit) {
if (!canvas) {
canvas = document.createElement('canvas');
canvas = document.createElement("canvas");
document.body.append(canvas);
}
this.bg = bg || 'white';
this.framerate = framerate || 60;
this.bg = bg || "white";
this.framerate = framerate;
canvas.width = width;
canvas.height = height;
canvas.width = fillScreen ? document.body.clientWidth : width;
canvas.height = fillScreen ? document.body.clientHeight : height;
if (fillScreen) {
const resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
this._canvas.width = entry.target.clientWidth;
this._canvas.height = entry.target.clientHeight;
// this.ctx = this.c
}
});
resizeObserver.observe(document.body);
}
this._canvas = canvas;
const ctx = canvas.getContext('2d');
console.log(ctx);
if (!ctx) throw 'Unable to initialize Doodler: Canvas context not found';
const ctx = canvas.getContext("2d");
if (!ctx) throw "Unable to initialize Doodler: Canvas context not found";
this.ctx = ctx;
postInit?.(this.ctx);
}
init() {
this._canvas.addEventListener('mousedown', e => this.onClick(e));
this._canvas.addEventListener('mouseup', e => this.offClick(e));
this._canvas.addEventListener('mousemove', e => {
const rect = this._canvas.getBoundingClientRect();
this.mouseX = e.clientX - rect.left;
this.mouseY = e.clientY - rect.top;
for (const d of this.draggables.filter(d => d.beingDragged)) {
d.point.add(e.movementX, e.movementY)
}
})
this._canvas.addEventListener("mousedown", (e) => this.onClick(e));
this._canvas.addEventListener("mouseup", (e) => this.offClick(e));
this._canvas.addEventListener("mousemove", (e) => this.onDrag(e));
this.startDrawLoop();
}
private timer?: number;
private lastFrameAt = 0;
private startDrawLoop() {
this.timer = setInterval(() => this.draw(), 1000 / this.framerate);
this.lastFrameAt = Date.now();
if (this.framerate) {
this.timer = setInterval(
() => this.draw(Date.now()),
1000 / this.framerate,
);
} else {
const cb = (t: number) => {
this.draw(t);
requestAnimationFrame(cb);
};
requestAnimationFrame(cb);
}
}
private draw() {
protected draw(time: number) {
const frameTime = time - this.lastFrameAt;
this.ctx.clearRect(0, 0, this.width, this.height);
this.ctx.fillStyle = this.bg;
this.ctx.fillRect(0, 0, this.width, this.height);
// for (const d of this.draggables.filter(d => d.beingDragged)) {
// d.point.set(this.mouseX,this.mouseY);
// }
for (const [i, l] of (this.layers || []).entries()) {
l(this.ctx, i);
l(this.ctx, i, frameTime);
this.drawDeferred();
}
this.drawUI();
this.lastFrameAt = time;
}
// Layer management
@ -104,11 +119,11 @@ export class Doodler {
}
deleteLayer(layer: layer) {
this.layers = this.layers.filter(l => l !== layer);
this.layers = this.layers.filter((l) => l !== layer);
}
moveLayer(layer: layer, index: number) {
let temp = this.layers.filter(l => l !== layer);
let temp = this.layers.filter((l) => l !== layer);
temp = [...temp.slice(0, index), layer, ...temp.slice(index)];
@ -125,7 +140,7 @@ export class Doodler {
this.ctx.stroke();
}
dot(at: Vector, style?: IStyle) {
this.setStyle({ ...style, weight: 1 })
this.setStyle({ ...style, weight: 1 });
this.ctx.beginPath();
this.ctx.arc(at.x, at.y, style?.weight || 1, 0, Constants.TWO_PI);
@ -195,21 +210,134 @@ export class Doodler {
this.ctx.restore();
}
drawImage(img: HTMLImageElement, at: Vector): void;
drawImage(img: HTMLImageElement, at: Vector, w: number, h: number): void;
drawImage(img: HTMLImageElement, at: Vector, w?: number, h?: number) {
w && h ? this.ctx.drawImage(img, at.x, at.y, w, h) : this.ctx.drawImage(img, at.x, at.y);
drawScaled(scale: number, cb: () => void) {
this.ctx.save();
this.ctx.transform(scale, 0, 0, scale, 0, 0);
cb();
this.ctx.restore();
}
drawSprite(img: HTMLImageElement, spritePos: Vector, sWidth: number, sHeight: number, at: Vector, width: number, height: number) {
this.ctx.drawImage(img, spritePos.x, spritePos.y, sWidth, sHeight, at.x, at.y, width, height);
drawWithAlpha(alpha: number, cb: () => void) {
this.ctx.save();
this.ctx.globalAlpha = Math.min(Math.max(alpha, 0), 1);
cb();
this.ctx.restore();
}
drawImage(img: CanvasImageSource, at: Vector): void;
drawImage(img: CanvasImageSource, at: Vector, w: number, h: number): void;
drawImage(img: CanvasImageSource, at: Vector, w?: number, h?: number) {
w && h
? this.ctx.drawImage(img, at.x, at.y, w, h)
: this.ctx.drawImage(img, at.x, at.y);
}
/**
* @description This method is VERY expensive and should be used sparingly - O(n^2) where n is weight. Beyond that, it doesn't work with transparency correctly since the image is overlaid multiple times in drawing and the resulting transparency is dependent on the weight provided
*
* @param img
* @param at
* @param style
*/
drawImageWithOutline(img: HTMLImageElement, at: Vector, style?: IStyle): void;
drawImageWithOutline(
img: HTMLImageElement,
at: Vector,
w: number,
h: number,
style?: IStyle,
): void;
drawImageWithOutline(
img: HTMLImageElement,
at: Vector,
w?: number | IStyle,
h?: number,
style?: IStyle,
) {
this.ctx.save();
const s = (typeof w === "number" || !w ? style?.weight : w.weight) || 1; // thickness scale
this.ctx.shadowColor =
(typeof w === "number" || !w
? style?.color || style?.fillColor
: w.color || w.strokeColor) || "red";
this.ctx.shadowBlur = 0;
// X offset loop
for (let x = -s; x <= s; x++) {
// Y offset loop
for (let y = -s; y <= s; y++) {
// Set shadow offset
this.ctx.shadowOffsetX = x;
this.ctx.shadowOffsetY = y;
// Draw image with shadow
typeof w === "number" && h
? this.ctx.drawImage(img, at.x, at.y, w, h)
: this.ctx.drawImage(img, at.x, at.y);
}
}
this.ctx.restore();
}
drawSprite(
img: HTMLImageElement,
spritePos: Vector,
sWidth: number,
sHeight: number,
at: Vector,
width: number,
height: number,
) {
this.ctx.drawImage(
img,
spritePos.x,
spritePos.y,
sWidth,
sHeight,
at.x,
at.y,
width,
height,
);
}
private deferredDrawings: (() => void)[] = [];
deferDrawing(cb: () => void) {
this.deferredDrawings.push(cb);
}
drawDeferred() {
while (this.deferredDrawings.length) {
this.deferredDrawings.pop()?.();
}
}
setStyle(style?: IStyle) {
const ctx = this.ctx;
ctx.fillStyle = style?.color || style?.fillColor || 'black';
ctx.strokeStyle = style?.color || style?.strokeColor || 'black';
ctx.fillStyle = style?.color || style?.fillColor || "black";
ctx.strokeStyle = style?.color || style?.strokeColor || "black";
ctx.lineWidth = style?.weight || 1;
ctx.textAlign = style?.textAlign || ctx.textAlign;
ctx.textBaseline = style?.textBaseline || ctx.textBaseline;
}
fillText(text: string, pos: Vector, maxWidth: number, style?: IStyle) {
this.setStyle(style);
// TODO: add text alignment to style
this.ctx.fillText(text, pos.x, pos.y, maxWidth);
}
strokeText(text: string, pos: Vector, maxWidth: number, style?: IStyle) {
this.setStyle(style);
// TODO: add text alignment to style
this.ctx.strokeText(text, pos.x, pos.y, maxWidth);
}
clearRect(at: Vector, width: number, height: number) {
this.ctx.clearRect(at.x, at.y, width, height);
}
// Interaction
@ -217,10 +345,16 @@ export class Doodler {
mouseX = 0;
mouseY = 0;
registerDraggable(point: Vector, radius: number, style?: IStyle & { shape: 'square' | 'circle' }) {
if (this.draggables.find(d => d.point === point)) return;
const id = this.addUIElement('circle', point, radius, { fillColor: '#5533ff50', strokeColor: '#5533ff50' })
registerDraggable(
point: Vector,
radius: number,
style?: IStyle & { shape: "square" | "circle" },
) {
if (this.draggables.find((d) => d.point === point)) return;
const id = this.addUIElement("circle", point, radius, {
fillColor: "#5533ff50",
strokeColor: "#5533ff50",
});
this.draggables.push({ point, radius, style, id });
}
unregisterDraggable(point: Vector) {
@ -229,7 +363,7 @@ export class Doodler {
this.removeUIElement(d.id);
}
}
this.draggables = this.draggables.filter(d => d.point !== point);
this.draggables = this.draggables.filter((d) => d.point !== point);
}
registerClickable(p1: Vector, p2: Vector, cb: () => void) {
@ -240,32 +374,41 @@ export class Doodler {
this.clickables.push({
onClick: cb,
checkBound: (p) => p.y >= top && p.x >= left && p.y <= bottom && p.x <= right
})
checkBound: (p) =>
p.y >= top && p.x >= left && p.y <= bottom && p.x <= right,
});
}
unregisterClickable(cb: () => void) {
this.clickables = this.clickables.filter(c => c.onClick !== cb);
this.clickables = this.clickables.filter((c) => c.onClick !== cb);
}
addDragEvents({
onDragEnd,
onDragStart,
point
}: { point: Vector, onDragEnd?: () => void, onDragStart?: () => void }) {
const d = this.draggables.find(d => d.point === point);
onDrag,
point,
}: {
point: Vector;
onDragEnd?: () => void;
onDragStart?: () => void;
onDrag?: (movement: { x: number; y: number }) => void;
}) {
const d = this.draggables.find((d) => d.point === point);
if (d) {
d.onDragEnd = onDragEnd;
d.onDragStart = onDragStart;
d.onDrag = onDrag;
}
}
onClick(e: MouseEvent) {
const mouse = new Vector(this.mouseX, this.mouseY)
const mouse = new Vector(this.mouseX, this.mouseY);
for (const d of this.draggables) {
if (d.point.dist(mouse) <= d.radius) {
d.beingDragged = true;
d.onDragStart?.call(null);
this.dragTarget = d;
} else d.beingDragged = false;
}
@ -281,34 +424,64 @@ export class Doodler {
d.beingDragged = false;
d.onDragEnd?.call(null);
}
this.dragTarget = undefined;
}
onDrag(e: MouseEvent) {
const rect = this._canvas.getBoundingClientRect();
this.mouseX = e.offsetX;
this.mouseY = e.offsetY;
// this.mouseX = e.clientX - rect.left;
// this.mouseY = e.clientY - rect.top;
for (const d of this.draggables.filter((d) => d.beingDragged)) {
d.point.add(e.movementX, e.movementY);
d.onDrag && d.onDrag({ x: e.movementX, y: e.movementY });
}
}
// UI Layer
uiElements: Map<string, [keyof uiDrawing, ...any]> = new Map();
private uiDrawing: uiDrawing = {
rectangle: (...args: any[]) => {
!args[3].noFill && this.fillRect(args[0], args[1], args[2], args[3])
!args[3].noStroke && this.drawRect(args[0], args[1], args[2], args[3])
!args[3].noFill && this.fillRect(args[0], args[1], args[2], args[3]);
!args[3].noStroke && this.drawRect(args[0], args[1], args[2], args[3]);
},
square: (...args: any[]) => {
!args[2].noFill && this.fillSquare(args[0], args[1], args[2])
!args[2].noStroke && this.drawSquare(args[0], args[1], args[2])
!args[2].noFill && this.fillSquare(args[0], args[1], args[2]);
!args[2].noStroke && this.drawSquare(args[0], args[1], args[2]);
},
circle: (...args: any[]) => {
!args[2].noFill && this.fillCircle(args[0], args[1], args[2])
!args[2].noStroke && this.drawCircle(args[0], args[1], args[2])
!args[2].noFill && this.fillCircle(args[0], args[1], args[2]);
!args[2].noStroke && this.drawCircle(args[0], args[1], args[2]);
},
}
};
private drawUI() {
for (const [shape, ...args] of this.uiElements.values()) {
this.uiDrawing[shape].apply(null, args as [])
this.uiDrawing[shape].apply(null, args as []);
}
}
addUIElement(shape: 'rectangle', at: Vector, width: number, height: number, style?: IStyle): string;
addUIElement(shape: 'square', at: Vector, size: number, style?: IStyle): string;
addUIElement(shape: 'circle', at: Vector, radius: number, style?: IStyle): string;
addUIElement(
shape: "rectangle",
at: Vector,
width: number,
height: number,
style?: IStyle,
): string;
addUIElement(
shape: "square",
at: Vector,
size: number,
style?: IStyle,
): string;
addUIElement(
shape: "circle",
at: Vector,
radius: number,
style?: IStyle,
): string;
addUIElement(shape: keyof uiDrawing, ...args: any[]) {
const id = crypto.randomUUID();
for (const arg of args) {
@ -331,6 +504,15 @@ interface IStyle {
noStroke?: boolean;
noFill?: boolean;
textAlign?: "center" | "end" | "left" | "right" | "start";
textBaseline?:
| "alphabetic"
| "top"
| "hanging"
| "middle"
| "ideographic"
| "bottom";
}
interface IDrawable {
@ -340,20 +522,21 @@ interface IDrawable {
type Draggable = {
point: Vector;
radius: number;
style?: IStyle & { shape: 'square' | 'circle' };
style?: IStyle & { shape: "square" | "circle" };
beingDragged?: boolean;
id: string;
onDragStart?: () => void;
onDragEnd?: () => void;
}
onDrag?: (dragDistance: { x: number; y: number }) => void;
};
type Clickable = {
onClick: () => void;
checkBound: (p: Vector) => boolean;
}
};
type uiDrawing = {
circle: () => void;
square: () => void;
rectangle: () => void;
}
};

BIN
cartoon fire.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 228 KiB

26
collision/aa.ts Normal file
View File

@ -0,0 +1,26 @@
import { Point } from "../geometry/vector.ts";
export type axisAlignedBoundingBox = {
w: number;
h: number;
} & Point;
export const axisAlignedCollision = (
aa1: axisAlignedBoundingBox,
aa2: axisAlignedBoundingBox,
) => {
return aa1.x < aa2.x + aa2.w &&
aa1.x + aa1.w > aa2.x &&
aa1.y < aa2.y + aa2.h &&
aa1.y + aa1.h > aa2.y;
};
export const axisAlignedContains = (
aa1: axisAlignedBoundingBox,
aa2: axisAlignedBoundingBox,
) => {
return aa1.x < aa2.x &&
aa1.y < aa2.y &&
aa1.x + aa1.w > aa2.x + aa2.w &&
aa1.y + aa1.h > aa2.y + aa2.h;
};

15
collision/circular.ts Normal file
View File

@ -0,0 +1,15 @@
import { Point } from "../geometry/vector.ts";
import { Vector } from "../mod.ts";
export type CircleLike = {
center: Point;
radius: number;
};
export const circularCollision = (c1: CircleLike, c2: CircleLike) => {
const center1 = new Vector(c1.center);
const center2 = new Vector(c2.center);
const maxDist = c1.radius + c2.radius;
return Vector.dist(center1, center2) < maxDist;
};

140
collision/sat.ts Normal file
View File

@ -0,0 +1,140 @@
import { Polygon } from "../geometry/polygon.ts";
import { SplineSegment } from "../geometry/spline.ts";
import { Vector } from "../geometry/vector.ts";
import { axisAlignedBoundingBox } from "./aa.ts";
import { CircleLike } from "./circular.ts";
export function satCollisionSpline(p: Polygon, spline: SplineSegment): boolean {
const numSegments = 100; // You can adjust the number of segments based on your needs
for (let i = 0; i < numSegments; i++) {
const t1 = i / numSegments;
const t2 = (i + 1) / numSegments;
const segmentStart = spline.getPointAtT(t1);
const segmentEnd = spline.getPointAtT(t2);
if (segmentIntersectsPolygon(p, segmentStart, segmentEnd)) {
return true;
}
}
return false;
}
export function satCollisionPolygon(poly: Polygon, poly2: Polygon): boolean {
for (const edge of poly.getEdges()) {
const axis = edge.copy().normal().normalize();
const proj1 = projectPolygonOntoAxis(poly, axis);
const proj2 = projectPolygonOntoAxis(poly2, axis);
if (!overlap(proj1, proj2)) return false;
}
for (const edge of poly2.getEdges()) {
const axis = edge.copy().normal().normalize();
const proj1 = projectPolygonOntoAxis(poly, axis);
const proj2 = projectPolygonOntoAxis(poly2, axis);
if (!overlap(proj1, proj2)) return false;
}
return true;
}
export function satCollisionCircle(p: Polygon, circle: CircleLike): boolean {
const center = new Vector(circle.center);
const nearest = p.getNearestPoint(center);
const axis = nearest.copy().sub(center).normalize();
const proj1 = projectPolygonOntoAxis(p, axis);
const proj2 = projectCircleOntoAxis(circle, axis);
if (!overlap(proj1, proj2)) return false;
for (const edge of p.getEdges()) {
const axis = edge.copy().normal().normalize();
const proj1 = projectPolygonOntoAxis(p, axis);
const proj2 = projectCircleOntoAxis(circle, axis);
if (!overlap(proj1, proj2)) return false;
}
return true;
}
export function satCollisionAABBCircle(
aabb: axisAlignedBoundingBox,
circle: CircleLike,
): boolean {
const p = new Polygon([
{ x: aabb.x, y: aabb.y },
{ x: aabb.x + aabb.w, y: aabb.y },
{ x: aabb.x + aabb.w, y: aabb.y + aabb.h },
{ x: aabb.x, y: aabb.y + aabb.h },
]);
return satCollisionCircle(p, circle);
}
function segmentIntersectsPolygon(
p: Polygon,
start: Vector,
end: Vector,
): boolean {
const edges = p.getEdges();
for (const edge of edges) {
// const axis = new Vector(-edge.y, edge.x).normalize();
const axis = edge.copy().normal().normalize();
const proj1 = projectPolygonOntoAxis(p, axis);
const proj2 = projectSegmentOntoAxis(start, end, axis);
if (!overlap(proj1, proj2)) {
return false; // No overlap, no intersection
}
}
return true; // Overlapping on all axes, intersection detected
}
function projectPolygonOntoAxis(
p: Polygon,
axis: Vector,
): { min: number; max: number } {
let min = Infinity;
let max = -Infinity;
for (const point of p.points) {
const dotProduct = point.copy().add(p.center).dot(axis);
min = Math.min(min, dotProduct);
max = Math.max(max, dotProduct);
}
return { min, max };
}
function projectSegmentOntoAxis(
start: Vector,
end: Vector,
axis: Vector,
): { min: number; max: number } {
const dotProductStart = start.dot(axis);
const dotProductEnd = end.dot(axis);
return {
min: Math.min(dotProductStart, dotProductEnd),
max: Math.max(dotProductStart, dotProductEnd),
};
}
function projectCircleOntoAxis(
c: CircleLike,
axis: Vector,
): { min: number; max: number } {
const dot = new Vector(c.center).dot(axis);
const min = dot - c.radius;
const max = dot + c.radius;
return { min, max };
}
function overlap(
proj1: { min: number; max: number },
proj2: { min: number; max: number },
): boolean {
return proj1.min <= proj2.max && proj1.max >= proj2.min;
}

View File

@ -2,13 +2,18 @@
"compilerOptions": {
"lib": [
"DOM",
"es2015"
"es2023"
],
"types": [
"./global.d.ts"
]
},
"tasks": {
"dev" : "deno bundle --watch main.ts bundle.js"
"dev": "deno bundle --watch main.ts bundle.js"
},
"imports": {
"std": "https://deno.land/std@0.205.0/mod.ts",
"std/": "https://deno.land/std@0.205.0/",
"dpng": "https://deno.land/x/dpng@0.7.5/mod.ts"
}
}

BIN
fire-joypixels.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 444 KiB

133
geometry/polygon.ts Normal file
View File

@ -0,0 +1,133 @@
import { axisAlignedBoundingBox } from "../collision/aa.ts";
import { CircleLike } from "../collision/circular.ts";
import { Vector } from "../mod.ts";
import { Point } from "./vector.ts";
export class Polygon {
points: Vector[];
center: Vector;
constructor(points: Point[]) {
this.points = points.map((p) => new Vector(p));
this.center = this.calcCenter();
}
draw(color?: string) {
for (let i = 0; i < this.points.length; i++) {
const p1 = this.points[i];
const p2 = this.points.at(i - this.points.length + 1)!;
doodler.line(p1.copy().add(this.center), p2.copy().add(this.center), {
color,
});
}
doodler.dot(this.center, { weight: 4, color: "yellow" });
}
calcCenter() {
if (!this.points.length) return new Vector();
const center = new Vector();
for (const point of this.points) {
center.add(point);
}
center.div(this.points.length);
return center;
}
_circularBoundingBox?: CircleLike;
get circularBoundingBox(): CircleLike {
this._circularBoundingBox = this.calculateCircularBoundingBox();
return this._circularBoundingBox;
}
private calculateCircularBoundingBox() {
let greatestDistance = 0;
for (const p of this.points) {
greatestDistance = Math.max(
p.copy().add(this.center).dist(this.center),
greatestDistance,
);
}
return {
center: this.center.copy(),
radius: greatestDistance,
};
}
_aabb?: axisAlignedBoundingBox;
get AABB(): axisAlignedBoundingBox {
this._aabb = this.recalculateAABB();
return this._aabb;
}
private recalculateAABB(): axisAlignedBoundingBox {
let smallestX, biggestX, smallestY, biggestY;
smallestX =
smallestY =
Infinity;
biggestX =
biggestY =
-Infinity;
for (const p of this.points) {
const temp = p.copy().add(this.center);
smallestX = Math.min(temp.x, smallestX);
biggestX = Math.max(temp.x, biggestX);
smallestY = Math.min(temp.y, smallestY);
biggestY = Math.max(temp.y, biggestY);
}
return {
x: smallestX + this.center.x,
y: smallestY + this.center.y,
w: biggestX - smallestX,
h: biggestY - smallestY,
};
}
static createPolygon(sides = 3, radius = 100) {
sides = Math.round(sides);
if (sides < 3) {
throw "You need at least 3 sides for a polygon";
}
const poly = new Polygon([]);
// figure out the angles required
const rotangle = (Math.PI * 2) / sides;
let angle = 0;
// loop through and generate each point
for (let i = 0; i < sides; i++) {
angle = (i * rotangle) + ((Math.PI - rotangle) * 0.5);
const pt = new Vector(Math.cos(angle) * radius, Math.sin(angle) * radius);
poly.points.push(pt);
}
poly.center = poly.calcCenter();
for (const p of poly.points) {
p.sub(poly.center);
}
return poly;
}
getEdges(): Vector[] {
const edges: Vector[] = [];
for (let i = 0; i < this.points.length; i++) {
const nextIndex = (i + 1) % this.points.length;
const edge = this.points[nextIndex].copy().add(this.center).sub(
this.points[i].copy().add(this.center),
);
edges.push(edge);
}
return edges;
}
getNearestPoint(p: Vector) {
let nearest = this.points[0];
for (const point of this.points) {
if (p.dist(point) < p.dist(nearest)) nearest = point;
}
return nearest.copy().add(this.center);
}
}

246
geometry/spline.ts Normal file
View File

@ -0,0 +1,246 @@
import { axisAlignedBoundingBox } from "../collision/aa.ts";
import { Point, Vector } from "./vector.ts";
export class SplineSegment {
points: [Vector, Vector, Vector, Vector];
length: number;
constructor(points: [Vector, Vector, Vector, Vector]) {
this.points = points;
this.length = this.calculateApproxLength(100);
}
draw(color?: string) {
const [a, b, c, d] = this.points;
doodler.drawBezier(a, b, c, d, {
strokeColor: color || "#ffffff50",
});
}
getPointAtT(t: number) {
const [a, b, c, d] = this.points;
const res = a.copy();
res.add(Vector.add(a.copy().mult(-3), b.copy().mult(3)).mult(t));
res.add(
Vector.add(
Vector.add(a.copy().mult(3), b.copy().mult(-6)),
c.copy().mult(3),
).mult(Math.pow(t, 2)),
);
res.add(
Vector.add(
Vector.add(a.copy().mult(-1), b.copy().mult(3)),
Vector.add(c.copy().mult(-3), d.copy()),
).mult(Math.pow(t, 3)),
);
return res;
}
getClosestPoint(v: Vector): [Vector, number, number] {
const samples = 25;
const resolution = 1 / samples;
let closest = this.points[0];
let closestDistance = this.points[0].dist(v);
let closestT = 0;
for (let i = 0; i < samples; i++) {
const point = this.getPointAtT(i * resolution);
const distance = v.dist(point);
if (distance < closestDistance) {
closest = point;
closestDistance = distance;
closestT = i * resolution;
}
}
return [closest, closestDistance, closestT];
}
getPointsWithinRadius(v: Vector, r: number) {
const points: [number, SplineSegment][] = [];
const samples = 25;
const resolution = 1 / samples;
for (let i = 0; i < samples + 1; i++) {
const point = this.getPointAtT(i * resolution);
const distance = v.dist(point);
if (distance < r) {
points.push([i * resolution, this]);
}
}
return points;
}
tangent(t: number) {
// dP(t) / dt = -3(1-t)^2 * P0 + 3(1-t)^2 * P1 - 6t(1-t) * P1 - 3t^2 * P2 + 6t(1-t) * P2 + 3t^2 * P3
const [a, b, c, d] = this.points;
const res = Vector.sub(b, a).mult(3 * Math.pow(1 - t, 2));
res.add(
Vector.add(
Vector.sub(c, b).mult(6 * (1 - t) * t),
Vector.sub(d, c).mult(3 * Math.pow(t, 2)),
),
);
return res;
}
doesIntersectCircle(x: number, y: number, r: number) {
const v = new Vector(x, y);
const samples = 25;
const resolution = 1 / samples;
let distance = Infinity;
let t;
for (let i = 0; i < samples - 1; i++) {
const a = this.getPointAtT(i * resolution);
const b = this.getPointAtT((i + 1) * resolution);
const ac = Vector.sub(v, a);
const ab = Vector.sub(b, a);
const d = Vector.add(Vector.vectorProjection(ac, ab), a);
const ad = Vector.sub(d, a);
const k = Math.abs(ab.x) > Math.abs(ab.y) ? ad.x / ab.x : ad.y / ab.y;
let dist;
if (k <= 0.0) {
dist = Vector.hypot2(v, a);
} else if (k >= 1.0) {
dist = Vector.hypot2(v, b);
}
dist = Vector.hypot2(v, d);
if (dist < distance) {
distance = dist;
t = i * resolution;
}
}
if (distance < r) return t;
return false;
}
intersectsCircle(circleCenter: Point, radius: number): boolean {
const numSegments = 100; // Initial number of segments
const minResolution = 10; // Minimum resolution to ensure accuracy
for (let i = 0; i < numSegments; i++) {
const t1 = i / numSegments;
const t2 = (i + 1) / numSegments;
const segmentStart = this.getPointAtT(t1);
const segmentEnd = this.getPointAtT(t2);
const segmentLength = Math.sqrt(
(segmentEnd.x - segmentStart.x) ** 2 +
(segmentEnd.y - segmentStart.y) ** 2,
);
// Dynamically adjust resolution based on segment length
const resolution = Math.max(
minResolution,
Math.ceil(numSegments * (segmentLength / radius)),
);
for (let j = 0; j <= resolution; j++) {
const t = j / resolution;
const point = this.getPointAtT(t);
const distance = Math.sqrt(
(point.x - circleCenter.x) ** 2 + (point.y - circleCenter.y) ** 2,
);
if (distance <= radius) {
return true; // Intersection detected
}
}
}
return false; // No intersection found
}
calculateApproxLength(resolution = 25) {
const stepSize = 1 / resolution;
const points: Vector[] = [];
for (let i = 0; i <= resolution; i++) {
const current = stepSize * i;
points.push(this.getPointAtT(current));
}
this.length =
points.reduce((acc: { prev?: Vector; length: number }, cur) => {
const prev = acc.prev;
acc.prev = cur;
if (!prev) return acc;
acc.length += cur.dist(prev);
return acc;
}, { prev: undefined, length: 0 }).length;
return this.length;
}
calculateEvenlySpacedPoints(spacing: number, resolution = 1) {
const points: Vector[] = [];
points.push(this.points[0]);
let prev = points[0];
let distSinceLastEvenPoint = 0;
let t = 0;
const div = Math.ceil(this.length * resolution * 10);
while (t < 1) {
t += 1 / div;
const point = this.getPointAtT(t);
distSinceLastEvenPoint += prev.dist(point);
if (distSinceLastEvenPoint >= spacing) {
const overshoot = distSinceLastEvenPoint - spacing;
const evenPoint = Vector.add(
point,
Vector.sub(point, prev).normalize().mult(overshoot),
);
distSinceLastEvenPoint = overshoot;
points.push(evenPoint);
prev = evenPoint;
}
prev = point;
}
return points;
}
private _aabb?: axisAlignedBoundingBox;
get AABB() {
if (!this._aabb) {
this._aabb = this.recalculateAABB();
}
return this._aabb;
}
recalculateAABB(): axisAlignedBoundingBox {
const numPoints = 100; // You can adjust the number of points based on your needs
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (let i = 0; i < numPoints; i++) {
const t = i / numPoints;
const point = this.getPointAtT(t);
minX = Math.min(minX, point.x);
minY = Math.min(minY, point.y);
maxX = Math.max(maxX, point.x);
maxY = Math.max(maxY, point.y);
}
return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };
}
}

View File

@ -2,15 +2,24 @@
import { Constants } from "./constants.ts";
export class Vector {
export class Vector implements Point {
x: number;
y: number;
z: number;
constructor(x = 0, y = 0, z = 0) {
this.x = x;
this.y = y;
this.z = z;
constructor();
constructor(p: Point);
constructor(x: number, y: number, z?: number);
constructor(x: number | Point = 0, y = 0, z = 0) {
if (typeof x === "number") {
this.x = x;
this.y = y;
this.z = z;
} else {
this.x = x.x;
this.y = x.y || y;
this.z = x.z || z;
}
}
set(x: number, y: number, z?: number): void;
@ -18,9 +27,11 @@ export class Vector {
set(v: [number, number, number]): void;
set(v: Vector | [number, number, number] | number, y?: number, z?: number) {
if (arguments.length === 1 && typeof v !== "number") {
this.set((v as Vector).x || (v as Array<number>)[0] || 0,
this.set(
(v as Vector).x || (v as Array<number>)[0] || 0,
(v as Vector).y || (v as Array<number>)[1] || 0,
(v as Vector).z || (v as Array<number>)[2] || 0);
(v as Vector).z || (v as Array<number>)[2] || 0,
);
} else {
this.x = v as number;
this.y = y || 0;
@ -43,7 +54,7 @@ export class Vector {
return (x * x + y * y + z * z);
}
setMag(len: number): void;
setMag(v: Vector, len: number): Vector
setMag(v: Vector, len: number): Vector;
setMag(v_or_len: Vector | number, len?: number) {
if (len === undefined) {
len = v_or_len as number;
@ -60,7 +71,7 @@ export class Vector {
add(x: number, y: number): Vector;
add(v: Vector): Vector;
add(v: Vector | number, y?: number, z?: number) {
if (arguments.length === 1 && typeof v !== 'number') {
if (arguments.length === 1 && typeof v !== "number") {
this.x += v.x;
this.y += v.y;
this.z += v.z;
@ -78,11 +89,12 @@ export class Vector {
sub(x: number, y: number, z: number): Vector;
sub(x: number, y: number): Vector;
sub(v: Vector): Vector;
sub(v: Vector | number, y?: number, z?: number) {
if (arguments.length === 1 && typeof v !== 'number') {
sub(v: Point): Vector;
sub(v: Vector | Point | number, y?: number, z?: number) {
if (arguments.length === 1 && typeof v !== "number") {
this.x -= v.x;
this.y -= v.y;
this.z -= v.z;
this.z -= v.z || 0;
} else if (arguments.length === 2) {
// 2D Vector
this.x -= v as number;
@ -95,7 +107,7 @@ export class Vector {
return this;
}
mult(v: number | Vector) {
if (typeof v === 'number') {
if (typeof v === "number") {
this.x *= v;
this.y *= v;
this.z *= v;
@ -107,7 +119,7 @@ export class Vector {
return this;
}
div(v: number | Vector) {
if (typeof v === 'number') {
if (typeof v === "number") {
this.x /= v;
this.y /= v;
this.z /= v;
@ -126,27 +138,25 @@ export class Vector {
this.y = s * prev_x + c * this.y;
return this;
}
dist(v: Vector) {
dist(v: Vector | Point) {
const dx = this.x - v.x,
dy = this.y - v.y,
dz = this.z - v.z;
dz = this.z - (v.z || 0);
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
dot(x: number, y: number, z: number): number;
dot(v: Vector): number;
dot(v: Vector | number, y?: number, z?: number) {
if (arguments.length === 1 && typeof v !== 'number') {
return (this.x * v.x + this.y * v.y + this.z * v.z);
if (arguments.length === 1 && typeof v !== "number") {
return (this.x * v.x) + (this.y * v.y) + (this.z * v.z);
}
return (this.x * (v as number) + this.y * y! + this.z * z!);
return (this.x * (v as number)) + (this.y * y!) + (this.z * z!);
}
cross(v: Vector) {
const x = this.x,
y = this.y,
z = this.z;
return new Vector(y * v.z - v.y * z,
z * v.x - v.z * x,
x * v.y - v.x * y);
return new Vector(y * v.z - v.y * z, z * v.x - v.z * x, x * v.y - v.x * y);
}
lerp(x: number, y: number, z: number): void;
lerp(v: Vector, amt: number): void;
@ -155,7 +165,7 @@ export class Vector {
return start + (stop - start) * amt;
};
let x, y: number;
if (arguments.length === 2 && typeof v_or_x !== 'number') {
if (arguments.length === 2 && typeof v_or_x !== "number") {
// given vector and amt
amt = amt_or_y;
x = v_or_x.x;
@ -202,10 +212,30 @@ export class Vector {
return new Vector(this.x, this.y, this.z);
}
drawDot() {
drawDot(color?: string) {
if (!doodler) return;
doodler.dot(this, {weight: 2, color: 'red'});
doodler.dot(this, { weight: 2, color: color || "red" });
}
draw(origin?: Point) {
if (!doodler) return;
const startPoint = origin ? new Vector(origin) : new Vector();
doodler.line(
startPoint,
startPoint.copy().add(this.copy().normalize().mult(100)),
);
}
normal(): Vector;
normal(v: Vector): Vector;
normal(v?: Vector) {
if (!v) return new Vector(-this.y, this.x);
const dx = v.x - this.x;
const dy = v.y - this.y;
return new Vector(-dy, dx);
}
static fromAngle(angle: number, v?: Vector) {
@ -261,9 +291,9 @@ export class Vector {
static lerp(v1: Vector, v2: Vector, amt: number) {
// non-static lerp mutates object, but this version returns a new vector
const retval = new Vector(v1.x, v1.y, v1.z);
retval.lerp(v2, amt);
return retval;
const val = new Vector(v1.x, v1.y, v1.z);
val.lerp(v2, amt);
return val;
}
static vectorProjection(v1: Vector, v2: Vector) {
@ -273,8 +303,46 @@ export class Vector {
v2.mult(sp);
return v2;
}
static vectorProjectionAndDot(v1: Vector, v2: Vector): [Vector, number] {
v2 = v2.copy();
v2.normalize();
const sp = v1.dot(v2);
v2.mult(sp);
return [v2, sp];
}
static hypot2(a: Vector, b: Vector) {
return Vector.dot(Vector.sub(a, b), Vector.sub(a, b))
return Vector.dot(Vector.sub(a, b), Vector.sub(a, b));
}
}
export class OriginVector extends Vector {
origin: Point;
get halfwayPoint() {
return {
x: (this.mag() / 2 * Math.sin(this.heading())) + this.origin.x,
y: (this.mag() / 2 * Math.cos(this.heading())) + this.origin.y,
};
}
constructor(origin: Point, p: Point) {
super(p.x, p.y, p.z);
this.origin = origin;
}
static from(origin: Point, p: Point) {
const v = {
x: p.x - origin.x,
y: p.y - origin.y,
};
return new OriginVector(origin, v);
}
}
export interface Point {
x: number;
y: number;
z?: number;
}

View File

@ -1,12 +1,32 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Doodler</title>
<style>
* {
/* image-rendering: pixelated; */
margin: 0;
}
body {
height: 100vh;
overflow: hidden;
}
img {
width: 50px;
border: 1px aqua solid;
margin: 2px;
}
</style>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>

50
init.ts Normal file
View File

@ -0,0 +1,50 @@
import { Doodler } from "./canvas.ts";
import { ZoomableDoodler } from "./zoomableCanvas.ts";
export type postInit = (ctx: CanvasRenderingContext2D) => void;
export function init(
opt: ZoomableDoodlerOptions,
zoomable: true,
postInit?: postInit,
): void;
export function init(
opt: DoodlerOptions,
zoomable: false,
postInit?: postInit,
): void;
export function init(
opt: DoodlerOptions | ZoomableDoodlerOptions,
zoomable: boolean,
postInit?: postInit,
) {
if (window.doodler) {
throw "Doodler has already been initialized in this window";
}
window.doodler = zoomable
? new ZoomableDoodler(opt, postInit)
: new Doodler(opt, postInit);
window.doodler.init();
}
type DoodlerOptionalOptions = {
canvas?: HTMLCanvasElement;
bg?: string;
framerate?: number;
};
type DoodlerRequiredOptions = {
width: number;
height: number;
fillScreen?: false;
} | {
width?: 0;
height?: 0;
fillScreen: true;
};
export type ZoomableDoodlerOptions = {
minScale?: number;
maxScale?: number;
} & DoodlerOptions;
export type DoodlerOptions = DoodlerOptionalOptions & DoodlerRequiredOptions;

233
main.ts
View File

@ -1,48 +1,213 @@
/// <reference types="./global.d.ts" />
import { Vector, initializeDoodler } from './mod.ts'
import { GIFAnimation } from "./animation/gif.ts";
import { SpriteAnimation } from "./animation/sprite.ts";
import { initializeDoodler, Vector } from "./mod.ts";
import { handleGIF } from "./processing/gif.ts";
import { ZoomableDoodler } from "./zoomableCanvas.ts";
import { axisAlignedCollision, axisAlignedContains } from "./collision/aa.ts";
import { circularCollision } from "./collision/circular.ts";
import {
satCollisionAABBCircle,
satCollisionCircle,
satCollisionSpline,
} from "./collision/sat.ts";
import { Polygon } from "./geometry/polygon.ts";
import { SplineSegment } from "./geometry/spline.ts";
// import { ZoomableDoodler } from "./zoomableCanvas.ts";
initializeDoodler({
width: 400,
height: 400
})
initializeDoodler(
{
// width: 2400,
fillScreen: true,
// height: 1200,
bg: "#333",
minScale: 1,
maxScale: 10,
},
true,
(ctx) => {
ctx.imageSmoothingEnabled = false;
},
);
const movingVector = new Vector(100, 300);
let angleMultiplier = 0;
const v = new Vector(30, 30);
doodler.registerDraggable(v, 20)
(doodler as ZoomableDoodler).minScale = .1;
// const movingVector = new Vector(100, 300);
// let angleMultiplier = 0;
// const v = new Vector(30, 30);
// doodler.registerDraggable(v, 20);
const img = new Image();
img.src = './EngineSprites.png'
img.hidden
document.body.append(img)
img.src = "./pixel fire.gif";
doodler.createLayer(() => {
const p = new Vector(500, 500);
const gif = new GIFAnimation("./fire-joypixels.gif", p, .5);
doodler.line(new Vector(100, 100), new Vector(200, 200))
doodler.dot(new Vector(300, 300))
doodler.fillCircle(movingVector, 6, { color: 'red' });
doodler.drawRect(new Vector(50, 50), movingVector.x, movingVector.y);
doodler.fillRect(new Vector(200, 250), 30, 10)
const spline = new SplineSegment([
new Vector({ x: -25, y: -25 }).mult(10).add(p),
new Vector({ x: 25, y: -25 }).mult(10).add(p),
new Vector({ x: -25, y: -25 }).mult(10).add(p),
new Vector({ x: -25, y: 25 }).mult(10).add(p),
]);
// poly.center = p.copy();
doodler.drawCenteredSquare(new Vector(200, 200), 40, { color: 'purple', weight: 5 })
doodler.drawBezier(new Vector(100, 150), movingVector, new Vector(150, 300), new Vector(100, 250))
const poly = Polygon.createPolygon(4);
const poly2 = Polygon.createPolygon(4);
let rotatedOrigin = new Vector(200, 200)
doodler.drawRotated(rotatedOrigin, Math.PI * angleMultiplier, () => {
doodler.drawCenteredSquare(rotatedOrigin, 30)
doodler.drawSprite(img, new Vector(0, 40), 80, 20, new Vector(160, 300), 80, 20)
})
poly.center = p.copy().add(400, 400);
poly2.center = p.copy().add(100, 100);
// poly.center.add(p);
doodler.createLayer((c, i, t) => {
// gif.draw(t);
// c.translate(500, 500);
for (let i = 0; i < c.canvas.width; i += 50) {
for (let j = 0; j < c.canvas.height; j += 50) {
doodler.drawSquare(new Vector(i, j), 50, { color: "#00000010" });
}
}
// const cir = poly2.circularHitbox;
// const t = spline.getPointsWithinRadius(
// new Vector(cir.center),
// cir.radius,
// ).map((t) => t[0]);
const intersects = satCollisionCircle(poly, poly2.circularBoundingBox);
const color = intersects ? "red" : "aqua";
movingVector.set((movingVector.x + 1) % 400, movingVector.y);
angleMultiplier += .001;
// const point = spline.getPointAtT(t || 0);
// point.drawDot("pink");
doodler.drawSprite(img, new Vector(0, 40), 80, 20, new Vector(100, 300), 80, 20)
// console.log(satCollision(
// ));
// for (let i = 0; i < 10; i++) {
// for (const i of t) {
// // const tan = spline.tangent(i / 10);
// const point = spline.getPointAtT(i);
// point.drawDot();
// }
spline.draw(color);
poly.draw(color);
poly2.draw(color);
// poly2.center.add(Vector.random2D());
const [gamepad] = navigator.getGamepads();
const deadzone = 0.05;
if (gamepad) {
const leftX = gamepad.axes[0];
const leftY = gamepad.axes[1];
const rightX = gamepad.axes[2];
const rightY = gamepad.axes[3];
// if (axisAlignedContains(poly2.aaHitbox, poly.aaHitbox)) {
// poly.center.add(
// new Vector(
// Math.min(Math.max(rightX - deadzone, 0), rightX + deadzone),
// Math.min(Math.max(rightY - deadzone, 0), rightY + deadzone),
// ).mult(10),
// );
// poly2.center.add(
// new Vector(
// Math.min(Math.max(leftX - deadzone, 0), leftX + deadzone),
// Math.min(Math.max(leftY - deadzone, 0), leftY + deadzone),
// ).mult(10),
// );
// }
// poly.center.add(
// new Vector(
// Math.min(Math.max(leftX - deadzone, 0), leftX + deadzone),
// Math.min(Math.max(leftY - deadzone, 0), leftY + deadzone),
// ).mult(10),
// );
let lMulti = 10;
const lMod = new Vector(
Math.min(Math.max(leftX - deadzone, 0), leftX + deadzone),
Math.min(Math.max(leftY - deadzone, 0), leftY + deadzone),
);
// let future = new Vector(cir.center).add(mod.copy().mult(lMulti--));
// while (spline.intersectsCircle(future, cir.radius)) {
// // if (lMulti === 0) {
// // lMulti = 1;
// // break;
// // }
// future = new Vector(cir.center).add(mod.copy().mult(lMulti--));
// }
poly.center.add(
lMod.mult(lMulti),
);
let rMulti = 10;
const rMod = new Vector(
Math.min(Math.max(rightX - deadzone, 0), rightX + deadzone),
Math.min(Math.max(rightY - deadzone, 0), rightY + deadzone),
);
// let future = new Vector(cir.center).add(mod.copy().mult(rMulti--));
// while (spline.intersectsCircle(future, cir.radius)) {
// // if (rMulti === 0) {
// // rMulti = 1;
// // break;
// // }
// future = new Vector(cir.center).add(mod.copy().mult(rMulti--));
// }
poly2.center.add(
rMod.mult(rMulti),
);
// (doodler as ZoomableDoodler).moveOrigin({ x: -rigthX * 5, y: -rigthY * 5 });
// if (gamepad.buttons[7].value) {
// (doodler as ZoomableDoodler).scaleAt(
// { x: 200, y: 200 },
// 1 + (gamepad.buttons[7].value / 5),
// );
// }
// if (gamepad.buttons[6].value) {
// (doodler as ZoomableDoodler).scaleAt(
// { x: 200, y: 200 },
// 1 - (gamepad.buttons[6].value / 5),
// );
// }
}
// doodler.drawImageWithOutline(img, p);
// doodler.line(new Vector(100, 100), new Vector(200, 200))
// doodler.dot(new Vector(300, 300))
// doodler.fillCircle(movingVector, 6, { color: 'red' });
// doodler.drawRect(new Vector(50, 50), movingVector.x, movingVector.y);
// doodler.fillRect(new Vector(200, 250), 30, 10)
// doodler.drawCenteredSquare(new Vector(200, 200), 40, { color: 'purple', weight: 5 })
// doodler.drawBezier(new Vector(100, 150), movingVector, new Vector(150, 300), new Vector(100, 250))
// let rotatedOrigin = new Vector(200, 200)
// doodler.drawRotated(rotatedOrigin, Math.PI * angleMultiplier, () => {
// doodler.drawCenteredSquare(rotatedOrigin, 30)
// doodler.drawSprite(img, new Vector(0, 40), 80, 20, new Vector(160, 300), 80, 20)
// })
// movingVector.set((movingVector.x + 1) % 400, movingVector.y);
// angleMultiplier += .001;
// doodler.drawSprite(img, new Vector(0, 40), 80, 20, new Vector(100, 300), 80, 20)
// doodler.drawScaled(1.5, () => {
// doodler.line(p.copy().add(-8, 10), p.copy().add(8, 10), {
// color: "grey",
// weight: 2,
// });
// doodler.line(p.copy().add(-8, -10), p.copy().add(8, -10), {
// color: "grey",
// weight: 2,
// });
// doodler.line(p, p.copy().add(0, 12), { color: "brown", weight: 4 });
// doodler.line(p, p.copy().add(0, -12), { color: "brown", weight: 4 });
// });
});
document.addEventListener('keyup', e => {
e.preventDefault();
if (e.key === ' ') {
doodler.unregisterDraggable(v);
}
})
// document.addEventListener("keyup", (e) => {
// e.preventDefault();
// if (e.key === " ") {
// doodler.unregisterDraggable(v);
// }
// });

16
mod.ts
View File

@ -1,5 +1,17 @@
/// <reference types="./global.d.ts" />
export { init as initializeDoodler } from './canvas.ts';
export { GIFAnimation } from "./animation/gif.ts";
export { SpriteAnimation } from "./animation/sprite.ts";
export { axisAlignedCollision, axisAlignedContains } from "./collision/aa.ts";
export { circularCollision } from "./collision/circular.ts";
export {
satCollisionAABBCircle,
satCollisionCircle,
satCollisionPolygon,
satCollisionSpline,
} from "./collision/sat.ts";
export { Vector } from "./geometry/vector.ts";
export { Polygon } from "./geometry/polygon.ts";
export { SplineSegment } from "./geometry/spline.ts";
export { Vector } from './geometry/vector.ts';
export { init as initializeDoodler } from "./init.ts";

BIN
pixel fire.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 769 B

573
processing/gif.ts Normal file
View File

@ -0,0 +1,573 @@
export type Frame = {
x: number;
y: number;
width: number;
height: number;
hasLocalPalette: boolean;
paletteOffset: number | null;
paletteSize: number | null;
dataOffset: number;
dataLength: number;
transparentIndex: number | null;
interlaced: boolean;
delay: number;
disposal: number;
};
/**
* @classdesc This class is a TS refactoring of 'omggif's GifReader constructor, I simply copy-pasta'd it to be able to include using a deno bundler since they currently do not work properly with npm packages. Due to this, if anything doesn't work, do NOT contact the original author for issues with this class
* @author original - Dean McNamee <dean@gmail.com>
* @author refactor - Emma Short <emma@cyborggrizzly.com>
*/
export class GifReader {
private buf: Uint8Array;
private p: number;
public width: number;
public height: number;
private globalPaletteOffset: number | null;
private globalPaletteSize: number | null;
private frames: Frame[];
private loopCountValue: number | null;
constructor(buf: Uint8Array) {
this.buf = buf;
this.p = 0;
this.width = 0;
this.height = 0;
this.globalPaletteOffset = null;
this.globalPaletteSize = null;
this.frames = [];
this.loopCountValue = null;
this.parseHeader();
this.parseFrames();
}
public numFrames(): number {
return this.frames.length;
}
public loopCount(): number | null {
return this.loopCountValue;
}
public frameInfo(frameNum: number): Frame {
if (frameNum < 0 || frameNum >= this.frames.length) {
throw new Error("Frame index out of range.");
}
return this.frames[frameNum];
}
public decodeAndBlitFrameBGRA(
frameNum: number,
pixels: Uint8ClampedArray,
): void {
const frame = this.frameInfo(frameNum);
const numPixels = frame.width * frame.height;
const indexStream = new Uint8Array(numPixels); // At most 8-bit indices.
GifReaderLZWOutputIndexStream(
this.buf,
frame.dataOffset,
indexStream,
numPixels,
);
const paletteOffset = frame.paletteOffset;
let trans = frame.transparentIndex;
if (trans === null) trans = 256;
// We are possibly just blitting to a portion of the entire frame.
// That is a subRect within the frameRect, so the additional pixels
// must be skipped over after we finished a scanline.
const frameWidth = frame.width;
const frameStride = this.width - frameWidth;
let xLeft = frameWidth; // Number of subRect pixels left in scanline.
// Output index of the top left corner of the subRect.
const opBeg = ((frame.y * this.width) + frame.x) * 4;
// Output index of what would be the left edge of the subRect, one row
// below it, i.e. the index at which an interlace pass should wrap.
const opEnd = ((frame.y + frame.height) * this.width + frame.x) * 4;
let op = opBeg;
let scanStride = frameStride * 4;
// Use scanStride to skip past the rows when interlacing. This is skipping
// 7 rows for the first two passes, then 3 then 1.
if (frame.interlaced === true) {
scanStride += this.width * 4 * 7; // Pass 1.
}
let interlaceSkip = 8; // Tracking the row interval in the current pass.
for (let i = 0, il = indexStream.length; i < il; ++i) {
const index = indexStream[i];
if (xLeft === 0) { // Beginning of new scan line
op += scanStride;
xLeft = frameWidth;
if (op >= opEnd) { // Catch the wrap to switch passes when interlacing.
scanStride = frameStride * 4 + this.width * 4 * (interlaceSkip - 1);
// interlaceSkip / 2 * 4 is interlaceSkip << 1.
op = opBeg + (frameWidth + frameStride) * (interlaceSkip << 1);
interlaceSkip >>= 1;
}
}
if (index === trans) {
op += 4;
} else {
const r = this.buf[(paletteOffset || 0) + index * 3];
const g = this.buf[(paletteOffset || 0) + index * 3 + 1];
const b = this.buf[(paletteOffset || 0) + index * 3 + 2];
pixels[op++] = b;
pixels[op++] = g;
pixels[op++] = r;
pixels[op++] = 255;
}
--xLeft;
}
}
public decodeAndBlitFrameRGBA(
frameNum: number,
pixels: Uint8ClampedArray,
): void {
const frame = this.frameInfo(frameNum);
const numPixels = frame.width * frame.height;
const indexStream = new Uint8Array(numPixels); // At most 8-bit indices.
GifReaderLZWOutputIndexStream(
this.buf,
frame.dataOffset,
indexStream,
numPixels,
);
// debugger;
const paletteOffset = frame.paletteOffset;
let trans = frame.transparentIndex;
if (trans === null) trans = 256;
// We are possibly just blitting to a portion of the entire frame.
// That is a subRect within the frameRect, so the additional pixels
// must be skipped over after we finished a scanline.
const frameWidth = frame.width;
const frameStride = this.width - frameWidth;
let xLeft = frameWidth; // Number of subRect pixels left in scanline.
// Output index of the top left corner of the subRect.
const opBeg = ((frame.y * this.width) + frame.x) * 4;
// Output index of what would be the left edge of the subRect, one row
// below it, i.e. the index at which an interlace pass should wrap.
const opEnd = ((frame.y + frame.height) * this.width + frame.x) * 4;
let op = opBeg;
let scanStride = frameStride * 4;
// Use scanStride to skip past the rows when interlacing. This is skipping
// 7 rows for the first two passes, then 3 then 1.
if (frame.interlaced === true) {
scanStride += this.width * 4 * 7; // Pass 1.
}
let interlaceSkip = 8; // Tracking the row interval in the current pass.
for (let i = 0, il = indexStream.length; i < il; ++i) {
const index = indexStream[i];
if (xLeft === 0) { // Beginning of new scan line
op += scanStride;
xLeft = frameWidth;
if (op >= opEnd) { // Catch the wrap to switch passes when interlacing.
scanStride = frameStride * 4 + this.width * 4 * (interlaceSkip - 1);
// interlaceSkip / 2 * 4 is interlaceSkip << 1.
op = opBeg + (frameWidth + frameStride) * (interlaceSkip << 1);
interlaceSkip >>= 1;
}
}
if (index === trans) {
op += 4;
} else {
const rI = (paletteOffset || 0) + index * 3;
const r = this.buf[rI];
const g = this.buf[rI + 1];
const b = this.buf[rI + 2];
pixels[op++] = r;
pixels[op++] = g;
pixels[op++] = b;
pixels[op++] = 255;
}
--xLeft;
}
}
// Additional private or public methods should be implemented below
private parseHeader(): void {
// Parse the GIF file header
if (
this.buf[this.p++] !== 0x47 || this.buf[this.p++] !== 0x49 ||
this.buf[this.p++] !== 0x46 ||
this.buf[this.p++] !== 0x38 || (this.buf[this.p++] + 1 & 0xfd) !== 0x38 ||
this.buf[this.p++] !== 0x61
) {
throw new Error("Invalid GIF 87a/89a header.");
}
}
private parseLogicalScreenDescriptor(): void {
// Parse the Logical Screen Descriptor block
}
private parseGlobalColorTable(): void {
// Parse the Global Color Table block if it exists
}
private parseFrames(): void {
const width = this.buf[this.p++] | this.buf[this.p++] << 8;
const height = this.buf[this.p++] | this.buf[this.p++] << 8;
const pf0 = this.buf[this.p++]; // <Packed Fields>.
const global_palette_flag = pf0 >> 7;
const num_global_colors_pow2 = pf0 & 0x7;
const num_global_colors = 1 << (num_global_colors_pow2 + 1);
const background = this.buf[this.p++];
this.buf[this.p++]; // Pixel aspect ratio (unused?).
let global_palette_offset = null;
let global_palette_size = null;
if (global_palette_flag) {
global_palette_offset = this.p;
global_palette_size = num_global_colors;
this.p += num_global_colors * 3; // Seek past palette.
}
let no_eof = true;
const frames = [];
let delay = 0;
let transparentIndex = null;
let disposal = 0; // 0 - No disposal specified.
let loopCount = null;
this.width = width;
this.height = height;
while (no_eof && this.p < this.buf.length) {
switch (this.buf[this.p++]) {
case 0x21: // Graphics Control Extension Block
switch (this.buf[this.p++]) {
case 0xff: // Application specific block
// Try if it's a Netscape block (with animation loop counter).
if (
this.buf[this.p] !== 0x0b || // 21 FF already read, check block size.
// NETSCAPE2.0
this.buf[this.p + 1] == 0x4e && this.buf[this.p + 2] == 0x45 &&
this.buf[this.p + 3] == 0x54 &&
this.buf[this.p + 4] == 0x53 &&
this.buf[this.p + 5] == 0x43 &&
this.buf[this.p + 6] == 0x41 &&
this.buf[this.p + 7] == 0x50 &&
this.buf[this.p + 8] == 0x45 &&
this.buf[this.p + 9] == 0x32 &&
this.buf[this.p + 10] == 0x2e &&
this.buf[this.p + 11] == 0x30 &&
// Sub-block
this.buf[this.p + 12] == 0x03 &&
this.buf[this.p + 13] == 0x01 && this.buf[this.p + 16] == 0
) {
this.p += 14;
loopCount = this.buf[this.p++] | this.buf[this.p++] << 8;
this.p++; // Skip terminator.
} else { // We don't know what it is, just try to get past it.
this.p += 12;
while (true) { // Seek through subblocks.
const block_size = this.buf[this.p++];
// Bad block size (ex: undefined from an out of bounds read).
if (!(block_size >= 0)) throw Error("Invalid block size");
if (block_size === 0) break; // 0 size is terminator
this.p += block_size;
}
}
break;
case 0xf9: { // Graphics Control Extension
if (this.buf[this.p++] !== 0x4 || this.buf[this.p + 4] !== 0) {
throw new Error("Invalid graphics extension block.");
}
const pf1 = this.buf[this.p++];
delay = this.buf[this.p++] | this.buf[this.p++] << 8;
transparentIndex = this.buf[this.p++];
if ((pf1 & 1) === 0) transparentIndex = null;
disposal = pf1 >> 2 & 0x7;
this.p++; // Skip terminator.
break;
}
// Plain Text Extension could be present and we just want to be able
// to parse past it. It follows the block structure of the comment
// extension enough to reuse the path to skip through the blocks.
case 0x01: // Plain Text Extension (fallthrough to Comment Extension)
case 0xfe: // Comment Extension.
while (true) { // Seek through subblocks.
const block_size = this.buf[this.p++];
// Bad block size (ex: undefined from an out of bounds read).
if (!(block_size >= 0)) throw Error("Invalid block size");
if (block_size === 0) break; // 0 size is terminator
this.p += block_size;
}
break;
default:
throw new Error(
"Unknown graphic control label: 0x" +
this.buf[this.p - 1].toString(16),
);
}
break;
case 0x2c: { // Image Descriptor.
const x = this.buf[this.p++] | this.buf[this.p++] << 8;
const y = this.buf[this.p++] | this.buf[this.p++] << 8;
const w = this.buf[this.p++] | this.buf[this.p++] << 8;
const h = this.buf[this.p++] | this.buf[this.p++] << 8;
const pf2 = this.buf[this.p++];
const local_palette_flag = pf2 >> 7;
const interlace_flag = pf2 >> 6 & 1;
const num_local_colors_pow2 = pf2 & 0x7;
const num_local_colors = 1 << (num_local_colors_pow2 + 1);
let palette_offset = global_palette_offset;
let palette_size = global_palette_size;
let has_local_palette = false;
if (local_palette_flag) {
has_local_palette = true;
palette_offset = this.p; // Override with local palette.
palette_size = num_local_colors;
this.p += num_local_colors * 3; // Seek past palette.
}
const data_offset = this.p;
this.p++; // codeSize
while (true) {
const block_size = this.buf[this.p++];
// Bad block size (ex: undefined from an out of bounds read).
if (!(block_size >= 0)) throw Error("Invalid block size");
if (block_size === 0) break; // 0 size is terminator
this.p += block_size;
}
this.frames.push({
x,
y,
width: w,
height: h,
hasLocalPalette: has_local_palette,
paletteOffset: palette_offset,
paletteSize: palette_size,
dataOffset: data_offset,
dataLength: this.p - data_offset,
transparentIndex: transparentIndex,
interlaced: !!interlace_flag,
delay: delay,
disposal: disposal,
});
break;
}
case 0x3b: // Trailer Marker (end of file).
no_eof = false;
break;
default:
throw new Error(
"Unknown gif block: 0x" + this.buf[this.p - 1].toString(16),
);
}
}
}
// private readSubBlocks(): string {
// // Read a series of sub-blocks
// return "";
// }
// private readBlockTerminator(): void {
// // Read a block terminator if necessary
// }
}
function GifReaderLZWOutputIndexStream(
codeStream: Uint8Array,
p: number,
output: Uint8Array,
outputLength: number,
) {
const minCodeSize = codeStream[p++];
const clear_code = 1 << minCodeSize;
const eoi_code = clear_code + 1;
let nextCode = eoi_code + 1;
let curCodeSize = minCodeSize + 1; // Number of bits per code.
// NOTE: This shares the same name as the encoder, but has a different
// meaning here. Here this masks each code coming from the code stream.
let codeMask = (1 << curCodeSize) - 1;
let curShift = 0;
let cur = 0;
let op = 0; // Output pointer.
let subBlockSize = codeStream[p++];
const codeTable = new Int32Array(4096); // Can be signed, we only use 20 bits.
let prevCode = null; // Track code-1.
while (true) {
// Read up to two bytes, making sure we always 12-bits for max sized code.
while (curShift < 16) {
if (subBlockSize === 0) break; // No more data to be read.
cur |= codeStream[p++] << curShift;
curShift += 8;
if (subBlockSize === 1) { // Never let it get to 0 to hold logic above.
subBlockSize = codeStream[p++]; // Next subBlock.
} else {
--subBlockSize;
}
}
if (curShift < curCodeSize) {
break;
}
const code = cur & codeMask;
cur >>= curCodeSize;
curShift -= curCodeSize;
if (code === clear_code) {
// We don't actually have to clear the table. This could be a good idea
// for greater error checking, but we don't really do any anyway. We
// will just track it with next_code and overwrite old entries.
nextCode = eoi_code + 1;
curCodeSize = minCodeSize + 1;
codeMask = (1 << curCodeSize) - 1;
// Don't update prev_code ?
prevCode = null;
continue;
} else if (code === eoi_code) {
break;
}
// We have a similar situation as the decoder, where we want to store
// variable length entries (code table entries), but we want to do in a
// faster manner than an array of arrays. The code below stores sort of a
// linked list within the code table, and then "chases" through it to
// construct the dictionary entries. When a new entry is created, just the
// last byte is stored, and the rest (prefix) of the entry is only
// referenced by its table entry. Then the code chases through the
// prefixes until it reaches a single byte code. We have to chase twice,
// first to compute the length, and then to actually copy the data to the
// output (backwards, since we know the length). The alternative would be
// storing something in an intermediate stack, but that doesn't make any
// more sense. I implemented an approach where it also stored the length
// in the code table, although it's a bit tricky because you run out of
// bits (12 + 12 + 8), but I didn't measure much improvements (the table
// entries are generally not the long). Even when I created benchmarks for
// very long table entries the complexity did not seem worth it.
// The code table stores the prefix entry in 12 bits and then the suffix
// byte in 8 bits, so each entry is 20 bits.
const chaseCode: number = code < nextCode ? code : prevCode as number;
// Chase what we will output, either {CODE} or {CODE-1}.
let chaseLength = 0;
let chase = chaseCode as number;
while (chase > clear_code) {
chase = codeTable[chase] >> 8;
++chaseLength;
}
const k = chase;
const op_end = op + chaseLength + (chaseCode !== code ? 1 : 0);
if (op_end > outputLength) {
console.log("Warning, gif stream longer than expected.");
return;
}
// Already have the first byte from the chase, might as well write it fast.
output[op++] = k;
op += chaseLength;
let b = op; // Track pointer, writing backwards.
if (chaseCode !== code) { // The case of emitting {CODE-1} + k.
output[op++] = k;
}
chase = chaseCode;
while (chaseLength--) {
chase = codeTable[chase];
output[--b] = chase & 0xff; // Write backwards.
chase >>= 8; // Pull down to the prefix code.
}
if (prevCode !== null && nextCode < 4096) {
codeTable[nextCode++] = prevCode << 8 | k;
if (nextCode >= codeMask + 1 && curCodeSize < 12) {
++curCodeSize;
codeMask = codeMask << 1 | 1;
}
}
prevCode = code;
}
if (op !== outputLength) {
console.log("Warning, gif stream shorter than expected.");
}
return output;
}
export function handleGIF(
data: Uint8Array,
) {
const framesBase64: ({ canvas: HTMLCanvasElement } & Frame)[] = [];
const reader = new GifReader(data);
for (let i = 0; i < reader.numFrames(); i++) {
const frameData = reader.frameInfo(i);
// const buf = new Uint8Array(frameData.width * frameData.height * 4);
const canvas = document.createElement("canvas");
canvas.width = reader.width;
canvas.height = reader.height;
const ctx = canvas.getContext("2d")!;
const imageData = ctx.createImageData(reader.width, reader.height);
reader.decodeAndBlitFrameRGBA(i, imageData.data);
ctx.putImageData(
imageData,
0,
0,
frameData.x,
frameData.y,
frameData.width,
frameData.height,
);
framesBase64.push({ ...frameData, canvas });
}
return {
w: reader.width,
h: reader.height,
frames: framesBase64,
};
}

BIN
skeleton.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 795 B

2
timing/EaseInOut.ts Normal file
View File

@ -0,0 +1,2 @@
export const easeInOut = (x: number) =>
x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2;

2
timing/Map.ts Normal file
View File

@ -0,0 +1,2 @@
export const map = (value: number, x1: number, y1: number, x2: number, y2: number) =>
(value - x1) * (y2 - x2) / (y1 - x1) + x2;

307
zoomableCanvas.ts Normal file
View File

@ -0,0 +1,307 @@
import { Doodler } from "./canvas.ts";
import { OriginVector, Point } from "./geometry/vector.ts";
import { DoodlerOptions, postInit, ZoomableDoodlerOptions } from "./init.ts";
import { easeInOut } from "./timing/EaseInOut.ts";
import { map } from "./timing/Map.ts";
type TouchEventCallback = (e: TouchEvent) => void;
export class ZoomableDoodler extends Doodler {
private scale = 1;
dragging = false;
private origin: Point = {
x: 0,
y: 0,
};
mouse = {
x: 0,
y: 0,
};
private previousTouchLength?: number;
private touchTimer?: number;
private hasDoubleTapped = false;
private zooming = false;
scaleAround: Point = { x: 0, y: 0 };
maxScale = 4;
minScale = 1;
constructor(options: ZoomableDoodlerOptions, postInit?: postInit) {
super(options, postInit);
this._canvas.addEventListener("wheel", (e) => {
this.scaleAtMouse(e.deltaY < 0 ? 1.1 : .9);
if (this.scale === 1) {
this.origin.x = 0;
this.origin.y = 0;
}
});
this._canvas.addEventListener("dblclick", (e) => {
e.preventDefault();
this.scale = 1;
this.origin.x = 0;
this.origin.y = 0;
this.ctx.setTransform(1, 0, 0, 1, 0, 0);
});
this._canvas.addEventListener("mousedown", (e) => {
e.preventDefault();
this.dragging = true;
});
this._canvas.addEventListener("mouseup", (e) => {
e.preventDefault();
this.dragging = false;
});
this._canvas.addEventListener("mouseleave", (_e) => {
this.dragging = false;
});
this._canvas.addEventListener("mousemove", (e) => {
const prev = this.mouse;
this.mouse = {
x: e.offsetX,
y: e.offsetY,
};
if (this.dragging && !this.dragTarget) this.drag(prev);
});
this._canvas.addEventListener("touchstart", (e) => {
e.preventDefault();
if (e.touches.length === 1) {
const t1 = e.touches.item(0);
if (t1) {
this.mouse = this.getTouchOffset({
x: t1.clientX,
y: t1.clientY,
});
}
// this.touchTimer = setTimeout(() => {
// this.dragging = true;
// }, 100)
} else {
clearTimeout(this.touchTimer);
}
});
this._canvas.addEventListener("touchend", (e) => {
if (e.touches.length !== 2) {
this.previousTouchLength = undefined;
}
switch (e.touches.length) {
case 1:
break;
case 0:
if (!this.zooming) {
this.events.get("touchend")?.map((cb) => cb(e));
}
break;
}
this.dragging = e.touches.length === 1;
clearTimeout(this.touchTimer);
});
this._canvas.addEventListener("touchmove", (e) => {
e.preventDefault();
if (e.touches.length === 2) {
const t1 = e.touches.item(0);
const t2 = e.touches.item(1);
if (t1 && t2) {
const vect = OriginVector.from(
this.getTouchOffset({
x: t1.clientX,
y: t1.clientY,
}),
{
x: t2.clientX,
y: t2.clientY,
},
);
if (this.previousTouchLength) {
const diff = this.previousTouchLength - vect.mag();
this.scaleAt(vect.halfwayPoint, diff < 0 ? 1.01 : .99);
this.scaleAround = { ...vect.halfwayPoint };
}
this.previousTouchLength = vect.mag();
}
}
if (e.touches.length === 1) {
this.dragging === true;
const t1 = e.touches.item(0);
if (t1) {
const prev = this.mouse;
this.mouse = this.getTouchOffset({
x: t1.clientX,
y: t1.clientY,
});
this.drag(prev);
}
}
});
this._canvas.addEventListener("touchstart", (e) => {
if (e.touches.length !== 1) return false;
if (!this.hasDoubleTapped) {
this.hasDoubleTapped = true;
setTimeout(() => this.hasDoubleTapped = false, 300);
return false;
}
// this.ctx.setTransform(1, 0, 0, 1, 0, 0);
// this.scale = 1;
// this.origin.x = 0;
// this.origin.y = 0;
if (this.scale > 1) {
this.frameCounter = map(this.scale, this.maxScale, 1, 0, 59);
this.zoomDirection = -1;
} else {
this.frameCounter = 0;
this.zoomDirection = 1;
}
if (this.zoomDirection > 0) {
this.scaleAround = { ...this.mouse };
}
this.events.get("doubletap")?.map((cb) => cb(e));
});
}
worldToScreen(x: number, y: number) {
x = x * this.scale + this.origin.x;
y = y * this.scale + this.origin.y;
return { x, y };
}
screenToWorld(x: number, y: number) {
x = (x - this.origin.x) / this.scale;
y = (y - this.origin.y) / this.scale;
return { x, y };
}
scaleAtMouse(scaleBy: number) {
if (this.scale === this.maxScale && scaleBy > 1) return;
this.scaleAt({
x: this.mouse.x,
y: this.mouse.y,
}, scaleBy);
}
scaleAt(p: Point, scaleBy: number) {
this.scale = Math.min(
Math.max(this.scale * scaleBy, this.minScale),
this.maxScale,
);
this.origin.x = p.x - (p.x - this.origin.x) * scaleBy;
this.origin.y = p.y - (p.y - this.origin.y) * scaleBy;
this.constrainOrigin();
}
moveOrigin(motion: Point) {
if (this.scale > 1) {
this.origin.x += motion.x;
this.origin.y += motion.y;
this.constrainOrigin();
}
}
drag(prev: Point) {
if (this.scale > 1) {
const xOffset = this.mouse.x - prev.x;
const yOffset = this.mouse.y - prev.y;
this.origin.x += xOffset;
this.origin.y += yOffset;
this.constrainOrigin();
}
}
constrainOrigin() {
this.origin.x = Math.min(
Math.max(
this.origin.x,
(-this._canvas.width * this.scale) + this._canvas.width,
),
0,
);
this.origin.y = Math.min(
Math.max(
this.origin.y,
(-this._canvas.height * this.scale) + this._canvas.height,
),
0,
);
}
draw(time: number) {
this.ctx.setTransform(
this.scale,
0,
0,
this.scale,
this.origin.x,
this.origin.y,
);
this.animateZoom();
this.ctx.fillStyle = this.bg;
this.ctx.fillRect(0, 0, this.width / this.scale, this.height / this.scale);
super.draw(time);
}
getTouchOffset(p: Point) {
const { x, y } = this._canvas.getBoundingClientRect();
const offsetX = p.x - x;
const offsetY = p.y - y;
return {
x: offsetX,
y: offsetY,
};
}
onDrag(e: MouseEvent): void {
const d = {
...e,
movementX: e.movementX / this.scale,
movementY: e.movementY / this.scale,
};
super.onDrag(d);
const { x, y } = this.screenToWorld(e.offsetX, e.offsetY);
this.mouseX = x;
this.mouseY = y;
}
zoomDirection = -1;
frameCounter = 60;
animateZoom() {
if (this.frameCounter < 60) {
const frame = easeInOut(map(this.frameCounter, 0, 59, 0, 1));
switch (this.zoomDirection) {
case 1:
{
this.scale = map(frame, 0, 1, 1, this.maxScale);
}
break;
case -1:
{
this.scale = map(frame, 0, 1, this.maxScale, 1);
}
break;
}
this.origin.x = this.scaleAround.x - (this.scaleAround.x * this.scale);
this.origin.y = this.scaleAround.y - (this.scaleAround.y * this.scale);
this.constrainOrigin();
this.frameCounter++;
}
}
events: Map<string, TouchEventCallback[]> = new Map();
registerEvent(
eventName: "touchend" | "touchstart" | "touchmove" | "doubletap",
cb: TouchEventCallback,
) {
let events = this.events.get(eventName);
if (!events) events = this.events.set(eventName, []).get(eventName)!;
events.push(cb);
}
}