personal-site/utils/draw.ts

37 lines
1,014 B
TypeScript
Raw Permalink Normal View History

2023-11-09 22:14:37 +00:00
import type { PointLike } from './point'
let ctx: CanvasRenderingContext2D
2023-11-10 05:35:01 +00:00
let volumeMultiplier: number
export function initDrawVars(ctx_: CanvasRenderingContext2D) {
2023-11-09 22:14:37 +00:00
ctx = ctx_
2023-11-10 05:35:01 +00:00
updateDrawVars()
2023-11-09 22:14:37 +00:00
}
2023-11-10 05:35:01 +00:00
export function updateDrawVars() {
2024-05-21 19:09:23 +00:00
volumeMultiplier = (ctx.canvas.width * ctx.canvas.height) / 150
ctx.lineWidth = 0.75
2023-11-09 22:14:37 +00:00
}
2023-11-10 05:35:01 +00:00
function getTransparency(point0: PointLike, point1: PointLike) {
const distanceSquared = (point0.x - point1.x) ** 2 + (point0.y - point1.y) ** 2
const transparency = (volumeMultiplier / distanceSquared) - 0.1
2023-11-09 22:14:37 +00:00
2023-11-10 05:35:01 +00:00
return Math.min(Math.floor(transparency * 255), 255)
}
export function drawLine(point0: PointLike, point1: PointLike) {
const transparency = getTransparency(point0, point1)
if (transparency <= 0)
2023-11-09 22:14:37 +00:00
return
let opacityHex = transparency.toString(16)
if (opacityHex.length === 1)
opacityHex = `0${opacityHex}`
ctx.strokeStyle = `#FFFFFF${opacityHex}`
ctx.beginPath()
ctx.moveTo(point0.x, point0.y)
ctx.lineTo(point1.x, point1.y)
ctx.stroke()
}