I am currently working on adjusting my canvas to fit within its container in a Vue component. When I call resizeCanvas() in the mounted hook, I notice that the container's height and width are both 0. How can I create a canvas that dynamically fits its container so that changes in the container size using CSS will automatically update the canvas? (Please excuse any language errors as English is not my first language)
<template lang="html">
<div class="container" ref="container">
<canvas ref="canvas" :width="width" :height="height"></canvas>
</div>
</template>
<script>
export default {
name: "monster",
data ()
{
return {
width: 512,
height: 512
}
}
methods: {
resizeCanvas(){
console.log(this.$refs.container.offsetWidth); // logs 0
this.width = this.$refs.container.offsetWidth
this.height = this.$refs.container.offsetWidth
}
},
mounted ()
{
console.log(this.$refs.container.offsetWidth) // logs 0
window.addEventListener("resize", this.resizeCanvas);
this.resizeCanvas()
},
unmounted() {
window.removeEventListener("resize", this.resizeCanvas);
},
}
</script>
<style lang="css" scoped>
.container {
width: 100%; height: 100%
}
</style>