组件部分
<template>
<view><canvas :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }" canvas-id="textCanvas"></canvas></view>
</template>
<script>
export default {
props: {
width: {
type: String,
default: '200'
},
height: {
type: String,
default: '200'
},
color: {
type: String,
default: '#999'
},
text: {
type: String,
default: ''
},
fontSize: {
type: String,
default: '14px'
}
},
data() {
return {
htmlSize: document.getElementsByTagName('html')[0].style.fontSize.replace(/px/g, '') || 16
};
},
computed: {
canvasWidth() {
return this.width;
},
canvasHeight() {
return Math.floor(this.htmlSize / (18.75 / this.height));
}
},
mounted() {
this.drawFun();
},
methods: {
drawFun() {
const context = uni.createCanvasContext('textCanvas', this);
context.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
const size = Math.floor(this.htmlSize / (18.75 / this.fontSize));
context.font = size + 'px PingFangSC-Regular';
context.fillStyle = this.color;
const viewLen = Math.floor(this.canvasWidth / size);
const canvasText = this.text.slice(0, viewLen) + (this.text.length > viewLen ? '...' : '');
context.fillText(canvasText, 0, size);
setTimeout(() => {
this.$nextTick(() => {
context.draw();
});
}, 100);
}
}
};
</script>
<style lang="scss"></style>
html 引用部分
<textCanvas color="#999" fontSize="7" text="白色纯棉四件套,厂家大促销活动喜欢赶紧买它" width="106" height="10"></textCanvas>