UNPKG

@spearwolf/twopoint5d

Version:

Create 2.5D realtime graphics and pixelart with WebGL and three.js

78 lines 3.02 kB
import { Vector2 } from 'three/webgpu'; export function parseAnchorPosition(anchorPosition) { if (!anchorPosition || anchorPosition === 'center') { return ['center', 'center']; } const parts = anchorPosition.split(' '); return [parts[0], parts[1]]; } export function calculateAnchorOffset(rect, view, anchorPosition, target = new Vector2()) { const [anchorY, anchorX] = parseAnchorPosition(anchorPosition); const diffX = rect.width - view.width; const diffY = rect.height - view.height; switch (anchorX) { case 'left': target.x = 0; break; case 'center': target.x = diffX / 2; break; case 'right': target.x = diffX; break; } switch (anchorY) { case 'top': target.y = 0; break; case 'center': target.y = diffY / 2; break; case 'bottom': target.y = diffY; break; } return target; } export function fitIntoRectangle(rect, specs, target = new Vector2()) { if ('pixelZoom' in specs) { target.copy(rect).divideScalar(specs.pixelZoom); } else if (specs.fit === 'fill') { target.copy(rect); } else if (specs.fit === 'contain' || specs.fit === 'cover') { if ('width' in specs && specs.width !== 0 && (!('height' in specs) || specs.height === 0)) { target.width = specs.width; target.height = rect.height * (specs.width / rect.width); } else if ((!('width' in specs) || specs.width === 0) && 'height' in specs && specs.height !== 0) { target.width = rect.width * (specs.height / rect.height); target.height = specs.height; } else if ('width' in specs && specs.width !== 0 && 'height' in specs && specs.height !== 0) { const rectRatio = rect.width / rect.height; const specsRatio = specs.width / specs.height; const isContain = specs.fit === 'contain'; if ((isContain && rectRatio > specsRatio) || (!isContain && rectRatio < specsRatio)) { target.width = rect.width * (specs.height / rect.height); target.height = specs.height; } else if ((isContain && rectRatio < specsRatio) || (!isContain && rectRatio > specsRatio)) { target.width = specs.width; target.height = rect.height * (specs.width / rect.width); } else { target.set(specs.width, specs.height); } } if ('minPixelZoom' in specs && rect.width / target.width < specs.minPixelZoom) { target.copy(rect).divideScalar(specs.minPixelZoom); } else if ('maxPixelZoom' in specs && rect.width / target.width > specs.maxPixelZoom) { target.copy(rect).divideScalar(specs.maxPixelZoom); } } return target; } //# sourceMappingURL=fitIntoRectangle.js.map