useSetViewportSize.ts 1.6 KB

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