I have a problem with accessing canvas with vue refs. The ref to the canvas doesn't properly respond to applied css height and width (it has still the old property). This leads to wrong canvas context (ctx) and drawing. The partial solution is shown in function "getPropperSize" in the code, but there has to be a better way. Has someone any idea what's going on and why the myCanvas variable behaves strangely.
<template>
<h1>Canvas</h1>
<button @click="getPropperSize">getPropperSize</button>
<button @click="drawRect">drawRect</button>
<canvas ref="myCanvas" id="canv"> </canvas>
</template>
<script>
import { onMounted, onUpdated, ref } from 'vue'
export default {
setup() {
const myCanvas = ref(null);
console.log(myCanvas)
let ctx = null
onMounted(() => {
//This will output 150 even it shuld be 500
console.log(myCanvas.value.height)
ctx = myCanvas.value.getContext('2d')
})
const getPropperSize = function(){
console.log(myCanvas.value.clientHeight)
console.log(myCanvas.value.clientWidth)
myCanvas.value.height = myCanvas.value.clientHeight
myCanvas.value.width = myCanvas.value.clientWidth
}
const drawRect = function(){
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, 150, 75);
}
return {myCanvas, getPropperSize, drawRect}
}
}
</script>
<style>
#canv{
height: 50vh;
width: 50vw;
border: 3px solid #73AD21;
}
</style>