HumanBreak/src/components/boxAnimate.vue

79 lines
1.7 KiB
Vue
Raw Normal View History

2022-11-16 23:01:23 +08:00
<template>
<canvas
:width="width ?? 32"
:height="height ?? 32"
2022-11-21 20:00:34 +08:00
:id="`box-animate-${id}`"
2022-11-16 23:01:23 +08:00
></canvas>
</template>
<script lang="tsx" setup>
2022-11-21 20:00:34 +08:00
import { onMounted, onUnmounted, onUpdated, ref } from 'vue';
2022-11-16 23:01:23 +08:00
import { addAnimate, removeAnimate } from '../plugin/animateController';
2022-11-21 20:00:34 +08:00
import { has } from '../plugin/utils';
const id = (Math.random() * 1e8).toFixed(0);
2022-11-16 23:01:23 +08:00
const props = defineProps<{
id: string;
2022-11-21 20:00:34 +08:00
noborder?: boolean;
2022-11-16 23:01:23 +08:00
width?: number;
height?: number;
}>();
2022-11-21 20:00:34 +08:00
let c: HTMLCanvasElement;
let ctx: CanvasRenderingContext2D;
let drawFn: () => void;
function draw() {
if (has(drawFn)) removeAnimate(drawFn);
2022-11-16 23:01:23 +08:00
const cls = core.getClsFromId(props.id);
const frames = core.getAnimateFrames(cls);
2022-11-21 20:00:34 +08:00
const w = props.width ?? 32;
const h = props.height ?? 32;
if (!props.noborder) {
c.style.border = '1.5px solid #ddd';
c.style.backgroundColor = '#222';
}
2022-11-16 23:01:23 +08:00
const scale = window.devicePixelRatio;
2022-11-21 20:00:34 +08:00
c.style.width = `${w}px`;
c.style.height = `${h}px`;
c.width = scale * w;
c.height = scale * h;
2022-11-16 23:01:23 +08:00
ctx.scale(scale, scale);
2022-11-21 20:00:34 +08:00
if (frames === 1) {
core.drawIcon(ctx, props.id, 0, 0, props.width, props.height);
} else {
drawFn = () => {
core.clearMap(ctx);
const frame = core.status.globalAnimateStatus % frames;
core.drawIcon(ctx, props.id, 0, 0, w, h, frame);
};
2022-11-16 23:01:23 +08:00
2022-11-21 20:00:34 +08:00
drawFn();
addAnimate(drawFn);
2022-11-16 23:01:23 +08:00
2022-11-21 20:00:34 +08:00
onUnmounted(() => {
removeAnimate(drawFn);
});
}
}
onMounted(() => {
c = document.getElementById(`box-animate-${id}`) as HTMLCanvasElement;
ctx = c.getContext('2d')!;
draw();
});
onUpdated(() => {
draw();
2022-11-16 23:01:23 +08:00
});
</script>
2022-11-21 20:00:34 +08:00
<style lang="less" scoped></style>