vue如何显示小于12px的字体,利用canvas

9 篇文章 0 订阅

组件部分

<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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值