帮我用canvas写几个竖着的文字用vue3
以下是一个简单的Vue3组件,用于在Canvas上绘制竖向文字:
<template>
<canvas ref="canvas"></canvas>
</template>
<script>
import { onMounted, watch } from "vue";
export default {
props: {
text: {
type: String,
required: true,
},
fontSize: {
type: Number,
default: 16,
},
fontColor: {
type: String,
default: "#000000",
},
fontFamily: {
type: String,
default: "sans-serif",
},
},
setup(props, { emit }) {
let canvas;
let ctx;
const drawText = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = props.fontColor;
ctx.font = `${props.fontSize}px ${props.fontFamily}`;
const x = canvas.width / 2;
const y = canvas.height / 2;
ctx.save();
ctx.translate(x, y);
ctx.rotate(-Math.PI / 2);
ctx.textAlign = "center";
ctx.fillText(props.text, 0, 0);
ctx.restore();
};
onMounted(() => {
canvas = props.canvas || document.querySelector("canvas");
ctx = canvas.getContext("2d");
drawText();
});
watch(
() => [props.text, props.fontSize, props.fontColor, props.fontFamily],
() => {
if (ctx) {
drawText();
}
}
);
return {};
},
};
</script>
<style scoped>
canvas {
width: 200px;
height: 400px;
}
</style>
你可以在父组件中使用它,并传递文字、字体大小、字体颜色和字体家族等参数:
<template>
<div>
<VerticalText text="竖向文字1" />
<VerticalText text="竖向文字2" fontSize="20" fontColor="#ff0000" />
<VerticalText text="竖向文字3" fontFamily="serif" />
</div>
</template>
<script>
import VerticalText from "./VerticalText";
export default {
components: {
VerticalText,
},
};
</script>
``
原文地址: https://www.cveoy.top/t/topic/cLyu 著作权归作者所有。请勿转载和采集!