【发布时间】:2021-12-15 12:39:07
【问题描述】:
我正在尝试使我的画布适合它的容器,在一个 vue 组件中。 我在挂载时触发 resizeCanvas(),但容器的高度和宽度为 0。 如何拥有适合其容器的画布,以便我可以使用 css 更改容器大小并更新画布? (对不起我的英语,我不流利)
<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>
【问题讨论】:
标签: javascript css vue.js html5-canvas