Skip to content

Commit

Permalink
widget: compass: Use reactive approach for re-rendering
Browse files Browse the repository at this point in the history
Old intervaled approach was very resource intensive and caused slow downs in the widget once in a while.
  • Loading branch information
rafaellehmkuhl committed Dec 23, 2023
1 parent 05fe880 commit 4a4a898
Showing 1 changed file with 29 additions and 11 deletions.
40 changes: 29 additions & 11 deletions src/components/widgets/Compass.vue
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
<script setup lang="ts">
import { useElementSize } from '@vueuse/core'
import gsap from 'gsap'
import { computed, onBeforeMount, ref, toRefs } from 'vue'
import { computed, nextTick, onBeforeMount, reactive, ref, toRefs, watch } from 'vue'
import Dialog from '@/components/Dialog.vue'
import Dropdown from '@/components/Dropdown.vue'
Expand All @@ -37,11 +37,6 @@ const compassRoot = ref()
const canvasRef = ref<HTMLCanvasElement | undefined>()
const canvasContext = ref()
// Object used to store current render state
const renderVariables = {
yawAngleDegrees: 0,
}
// Angles used for the main marks
const mainAngles = {
[0]: 'N',
Expand Down Expand Up @@ -181,9 +176,28 @@ const renderCanvas = (): void => {
ctx.stroke()
}
// Update canvas at 60fps
setInterval(() => {
const angleDegrees = degrees(store.attitude.yaw ?? 0)
/**
* Deal with high frequency update and decrease cpu usage when drawing low degrees changes
*/
const yaw = ref(0)
let oldYaw: number | undefined = undefined
watch(store.attitude, (attitude) => {
const yawDiff = Math.abs(degrees(attitude.yaw - (oldYaw || 0)))
if (yawDiff > 0.1) {
oldYaw = attitude.yaw
yaw.value = degrees(store.attitude.yaw)
}
})
// eslint-disable-next-line jsdoc/require-jsdoc
type RenderVariables = { yawAngleDegrees: number }
// Object used to store current render state
const renderVariables = reactive<RenderVariables>({ yawAngleDegrees: 0 })
// Update the X position of each line in the render variables with GSAP to smooth the transition
watch(yaw, () => {
const angleDegrees = yaw.value
const fullRangeAngleDegrees = angleDegrees < 0 ? angleDegrees + 360 : angleDegrees
const fromWestToEast = renderVariables.yawAngleDegrees > 270 && fullRangeAngleDegrees < 90
Expand All @@ -198,8 +212,12 @@ setInterval(() => {
} else {
gsap.to(renderVariables, 0.1, { yawAngleDegrees: fullRangeAngleDegrees })
}
renderCanvas()
}, 1000 / 60)
})
// Update canvas whenever reference variables changes
watch(renderVariables, () => {
nextTick(() => renderCanvas())
})
</script>

<style scoped>
Expand Down

0 comments on commit 4a4a898

Please sign in to comment.