|
| 1 | +import { |
| 2 | + defineComponent, |
| 3 | + PropType, |
| 4 | + ref, |
| 5 | + h, |
| 6 | + isVue2, |
| 7 | + computed, |
| 8 | + onMounted, |
| 9 | + onBeforeUnmount, |
| 10 | +} from 'vue-demi' |
| 11 | +import type UnityWebgl from 'unity-webgl' |
| 12 | + |
| 13 | +let unityInstanceIdentifier: number = 0 |
| 14 | + |
| 15 | +function cssUnit(val: string | number): string | number { |
| 16 | + return isNaN(val as unknown as number) ? val : val + 'px' |
| 17 | +} |
| 18 | + |
| 19 | +export default defineComponent({ |
| 20 | + name: 'UnityWebglComponent', |
| 21 | + props: { |
| 22 | + unity: { |
| 23 | + type: Object as PropType<UnityWebgl>, |
| 24 | + }, |
| 25 | + width: { |
| 26 | + type: [String, Number] as PropType<string | number>, |
| 27 | + default: '100%', |
| 28 | + }, |
| 29 | + height: { |
| 30 | + type: [String, Number] as PropType<string | number>, |
| 31 | + default: '100%', |
| 32 | + }, |
| 33 | + tabindex: { |
| 34 | + type: [Number, String] as PropType<number | string>, |
| 35 | + }, |
| 36 | + }, |
| 37 | + setup(props) { |
| 38 | + const canvas = ref(null) |
| 39 | + unityInstanceIdentifier++ |
| 40 | + |
| 41 | + const canvasStyle = computed(() => { |
| 42 | + return { |
| 43 | + width: cssUnit(props.width), |
| 44 | + height: cssUnit(props.height), |
| 45 | + } |
| 46 | + }) |
| 47 | + const attrs: Record<string, string | number> = { |
| 48 | + id: `unity-canvas-${unityInstanceIdentifier}`, |
| 49 | + } |
| 50 | + if (props.tabindex || props.tabindex === 0) { |
| 51 | + attrs.tabindex = props.tabindex |
| 52 | + } |
| 53 | + |
| 54 | + onMounted(() => { |
| 55 | + if (canvas.value) { |
| 56 | + props.unity?.create(canvas.value) |
| 57 | + } |
| 58 | + }) |
| 59 | + onBeforeUnmount(() => { |
| 60 | + props.unity?.unsafe_unload() |
| 61 | + }) |
| 62 | + |
| 63 | + return () => |
| 64 | + h( |
| 65 | + 'canvas', |
| 66 | + isVue2 |
| 67 | + ? { |
| 68 | + ref: canvas, |
| 69 | + attrs, |
| 70 | + style: canvasStyle.value, |
| 71 | + } |
| 72 | + : { |
| 73 | + ref: canvas, |
| 74 | + style: canvasStyle.value, |
| 75 | + ...attrs, |
| 76 | + } |
| 77 | + ) |
| 78 | + }, |
| 79 | +}) |
0 commit comments