UNPKG

js-draw

Version:

Draw pictures using a pen, touchscreen, or mouse! JS-draw is a drawing library for JavaScript and TypeScript.

57 lines (56 loc) 2.12 kB
import { Mat33 } from '@js-draw/math'; // Represents a cached renderer/canvas // This is not a [CacheNode] -- it handles cached renderers and does not have sub-renderers. export default class CacheRecord { constructor(onBeforeDeallocCallback, cacheState) { this.onBeforeDeallocCallback = onBeforeDeallocCallback; this.cacheState = cacheState; this.allocd = false; // For debugging this.allocCount = 0; this.renderer = cacheState.props.createRenderer(); this.lastUsedCycle = -1; this.allocd = true; } startRender() { this.lastUsedCycle = this.cacheState.currentRenderingCycle; if (!this.allocd) { throw new Error("Only alloc'd canvases can be rendered to"); } return this.renderer; } dealloc() { this.onBeforeDeallocCallback?.(); this.allocd = false; this.onBeforeDeallocCallback = null; this.lastUsedCycle = 0; } isAllocd() { return this.allocd; } realloc(newDeallocCallback) { if (this.allocd) { this.dealloc(); } this.allocd = true; this.onBeforeDeallocCallback = newDeallocCallback; this.lastUsedCycle = this.cacheState.currentRenderingCycle; this.allocCount++; } getLastUsedCycle() { return this.lastUsedCycle; } // Returns the transformation that maps [drawTo] to this' renderable region // (i.e. a [cacheProps.blockResolution]-sized rectangle with top left at (0, 0)) getTransform(drawTo) { const transform = Mat33.scaling2D(this.cacheState.props.blockResolution.x / drawTo.size.x).rightMul(Mat33.translation(drawTo.topLeft.times(-1))); return transform; } setRenderingRegion(drawTo) { const transform = this.getTransform(drawTo); this.renderer.setTransform(transform); // The visible region may be slightly larger than where we're actually drawing // to (because of rounding). this.renderer.overrideVisibleRect(drawTo.grownBy(1 / transform.getScaleFactor())); } }