leaky-ships/leaky-ships/components/Gamefield/Ship.tsx
2023-07-11 19:25:44 +02:00

62 lines
1.5 KiB
TypeScript

import classNames from "classnames"
import { CSSProperties, useEffect, useRef } from "react"
import { ShipProps } from "../../interfaces/frontend"
const sizes: { [n: number]: number } = {
2: 96,
3: 144,
4: 196,
}
function Ship({
props: { size, variant, x, y, orientation },
preview,
warn,
color,
}: {
props: ShipProps
preview?: boolean
warn?: boolean
color?: string
}) {
const filename = `ship_blue_${size}x_${variant}.gif`
const canvasRef = useRef<HTMLCanvasElement>(null)
useEffect(() => {
const canvas = canvasRef.current
const ctx = canvas?.getContext("2d")
if (!canvas || !ctx) return
const gif = new Image()
gif.src = "/assets/" + filename
// Load the GIF and start rendering
gif.onload = function () {
// Set the canvas size to match the GIF dimensions
canvas.width = orientation === "h" ? sizes[size] : 48
canvas.height = orientation === "v" ? sizes[size] : 48
if (orientation === "v")
// Rotate the canvas by 90 degrees
ctx.rotate((90 * Math.PI) / 180)
// Draw the rotated GIF
ctx.drawImage(gif, 0, orientation === "h" ? 0 : -48, sizes[size], 48)
}
}, [filename, orientation, size, x, y])
return (
<div
className={classNames("ship", "s" + size, orientation, {
preview: preview,
warn: warn,
})}
style={
{ "--x": x, "--y": y, "--color": color ?? "limegreen" } as CSSProperties
}
>
<canvas ref={canvasRef} />
</div>
)
}
export default Ship