我做了一个canvas组件,想让他自适应其对应的div,但是我修改了data之后没办法渲染出来,也没办法让canvas按照div的宽改变它的宽,请问这怎么解决:
canvas组件代码:
<template>
<div>
<canvas :id="id" :width="width" :height="height"></canvas>
</div>
</template>
<script>
export default {
data() {
return {};
},
props: {
id: String,
width: Number,
height: Number,
textContent: String,
textColor: String,
textSize: String
},
mounted() {
this.renderTitle();
},
methods: {
renderTitle() {
let c = document.getElementById(this.id);
let ctx = c.getContext("2d");
let my_gradient = ctx.createLinearGradient(0, 0, this.width, 0);
my_gradient.addColorStop(0, "#142640");
my_gradient.addColorStop(0.5, "#1f395f");
my_gradient.addColorStop(1, "#142640");
ctx.fillStyle = my_gradient;
ctx.fillRect(0, 0, this.width, this.height);
ctx.font = this.textSize;
ctx.fillStyle = this.textColor;
ctx.textAlign = "center";
ctx.fillText(this.textContent, this.width / 2, this.height / 2 + 6);
}
}
};
</script>
div的代码:
<template>
<div class="RightTop" ref="RightTop" style="width: 100%;height: 280px;">
<titleName
id="RightTopTitle"
:width="width"
:height="height"
:textContent="textContent"
:textColor="textColor"
:textSize="textSize"
></titleName>
</div>
</template>
<script>
import titleName from "@/components/titleName.vue";
export default {
name: "ASKs.vue",
data() {
return {
width: 600,
height: 48,
textContent: "前后12小时运能分析",
textColor: "#34ffff",
textSize: "16px Georgia"
};
},
components: { titleName },
mounted() {
this.kuangao();
},
methods: {
kuangao(){
this.width=800//能改,但是渲染不出来
console.log(this.width)
}
}
}
</script>
<style scoped>
.RightTop {
/* width: 100%;
height: 280px; */
margin-bottom: 20px;
border: 2px #336699 dotted;
}
</style>
应该怎么做才能让canvas不仅能渲染出来还能自适应div宽高呢?
canvas
在使用的时候,好像是必须要设定确定的width
和height
,不然没办法渲染。如果是要适配,就要变量来控制宽高
canvas
宽高变动后,都会清空画布,需要重新渲染