useViewportSize.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { ref, computed, onMounted, onUnmounted, Ref, watch } from 'vue'
  2. import { MutationTypes, useStore } from '@/store'
  3. import { VIEWPORT_SIZE, VIEWPORT_ASPECT_RATIO } from '@/configs/canvas'
  4. export default (canvasRef: Ref<HTMLElement | undefined>) => {
  5. const viewportLeft = ref(0)
  6. const viewportTop = ref(0)
  7. const store = useStore()
  8. const canvasPercentage = computed(() => store.state.canvasPercentage)
  9. const setViewportSize = () => {
  10. if(!canvasRef.value) return
  11. const canvasWidth = canvasRef.value.clientWidth
  12. const canvasHeight = canvasRef.value.clientHeight
  13. if(canvasHeight / canvasWidth > VIEWPORT_ASPECT_RATIO) {
  14. const viewportActualWidth = canvasWidth * (canvasPercentage.value / 100)
  15. store.commit(MutationTypes.SET_CANVAS_SCALE, viewportActualWidth / VIEWPORT_SIZE)
  16. viewportLeft.value = (canvasWidth - viewportActualWidth) / 2
  17. viewportTop.value = (canvasHeight - viewportActualWidth * VIEWPORT_ASPECT_RATIO) / 2
  18. }
  19. else {
  20. const viewportActualHeight = canvasHeight * (canvasPercentage.value / 100)
  21. store.commit(MutationTypes.SET_CANVAS_SCALE, viewportActualHeight / (VIEWPORT_SIZE * VIEWPORT_ASPECT_RATIO))
  22. viewportLeft.value = (canvasWidth - viewportActualHeight / VIEWPORT_ASPECT_RATIO) / 2
  23. viewportTop.value = (canvasHeight - viewportActualHeight) / 2
  24. }
  25. }
  26. watch(canvasPercentage, setViewportSize)
  27. const viewportStyles = computed(() => ({
  28. width: VIEWPORT_SIZE,
  29. height: VIEWPORT_SIZE * VIEWPORT_ASPECT_RATIO,
  30. left: viewportLeft.value,
  31. top: viewportTop.value,
  32. }))
  33. const resizeObserver = new ResizeObserver(setViewportSize)
  34. onMounted(() => {
  35. if(canvasRef.value) resizeObserver.observe(canvasRef.value)
  36. })
  37. onUnmounted(() => {
  38. if(canvasRef.value) resizeObserver.unobserve(canvasRef.value)
  39. })
  40. return {
  41. viewportStyles,
  42. }
  43. }