<template>
    <canvas width="500" height="300" ref="canvas"></canvas>
</template>

<script setup>
import { ref, onMounted, watch } from "vue"

const props = defineProps({
    time: Number
})
const canvas = ref(null)
let ctx = null

watch(() => props.time, () => {
    if (ctx) {
        initCanvas()
    }
})

onMounted(() => {
    initCanvas()
})

function initCanvas() {

    canvas.value.height = canvas.value.height

    ctx = canvas.value?.getContext('2d')
    ctx.translate(canvas.value.width / 2, canvas.value.height)
    ctx.scale(1, -1)

    drawBranch(ctx, [0, 0], 15, 56, 90)
}

function drawRound(ctx, v0) {
    ctx.beginPath();
    ctx.arc(...v0, 6, 0, 2 * Math.PI);
    ctx.fillStyle = "#8DB1A9"
    ctx.fill();
}

/**
 * 
 * @param {CanvasRenderingContext2D} ctx 2d 绘图上下文
 * @param {[number, number]} v0 起点坐标
 * @param {number} thick 树枝粗细
 * @param {number} len 一截树枝长短
 * @param {number} dir 倾斜角度
 */
function drawBranch(ctx, v0, thick, len, dir) {
    if ((thick < 5 && Math.random() < 0.3)) return;
    if (thick < 2) {
        drawRound(ctx, v0)
        return;
    }
    ctx.beginPath();
    ctx.moveTo(...v0);
    const v1 = [
        v0[0] + len * Math.cos((dir * Math.PI) / 180),
        v0[1] + len * Math.sin((dir * Math.PI) / 180)
    ]
    ctx.lineTo(...v1);
    ctx.strokeStyle = "#333";
    ctx.lineCap = "round";
    ctx.lineWidth = thick;
    ctx.stroke();

    drawBranch(ctx, v1, thick * 0.8, len * 0.8, dir + Math.random() * 46);
    drawBranch(ctx, v1, thick * 0.8, len * 0.8, dir - Math.random() * 46);
}
</script>

<style>
canvas {
    position: absolute;
    right: 10px;
    bottom: 10px;
}
</style>