项目中需要根据选择的印章名称,动态生成印章 ,印章下方显示当前的日期 代码如下
<template><div><label for="name">选择名称:</label><select id="name" v-model="selectedName"><option value="name1">名称1</option><option value="name2">名称2</option><option value="name3">名称3</option></select><button @click="generateStampImage">生成印章图片</button><div ref="stampContainer" v-if="stampGenerated"><img :src="stampImage" alt="印章" /></div></div>
</template>export default {data() {return {selectedName: '',stampGenerated: false,stampImage: ''};},
methods: {generateStampImage() {const stampText = this.selectedName;const canvas = document.createElement("canvas");canvas.width = 100; // 缩小印章尺寸canvas.height = 100;const ctx = canvas.getContext("2d");// 绘制圆形边框ctx.beginPath();ctx.arc(80, 80, 75, 0, 2 * Math.PI, false);ctx.fillStyle = "white";ctx.fill();ctx.lineWidth = 3;ctx.strokeStyle = "red";ctx.stroke();// 绘制五角星this.drawStar(ctx, 80, 80, 5, 30, 15); // 适当调整五角星大小ctx.fillStyle = "red";ctx.fill();// 绘制弧形文本this.drawCircularText(ctx, stampText, 80, 80, 60, -Math.PI / 2, "red"); // 调整文本的起始角度// 绘制日期ctx.font = "14px Arial";ctx.fillStyle = "red";ctx.textAlign = "center";ctx.fillText(this.currentDate, 80, 120); // 日期显示在五角星下方const stampImage = canvas.toDataURL("image/png");this.stampGenerated = true;this.stampImage = stampImage;},drawStar(ctx, cx, cy, spikes, outerRadius, innerRadius) {let rot = (Math.PI / 2) * 3;let x = cx;let y = cy;const step = Math.PI / spikes;ctx.beginPath();ctx.moveTo(cx, cy - outerRadius);for (let i = 0; i < spikes; i++) {x = cx + Math.cos(rot) * outerRadius;y = cy + Math.sin(rot) * outerRadius;ctx.lineTo(x, y);rot += step;x = cx + Math.cos(rot) * innerRadius;y = cy + Math.sin(rot) * innerRadius;ctx.lineTo(x, y);rot += step;}ctx.lineTo(cx, cy - outerRadius);ctx.closePath();},drawCircularText(ctx, text, x, y, radius, color) {ctx.fillStyle = color;ctx.font = '16px Arial';ctx.textBaseline = 'middle';let startAngle = -Math.PI; // 开始于水平左侧let totalAngle = 0; // 计算总角度// 计算文本占据的总角度for (let i = 0; i < text.length; i++) {totalAngle += ctx.measureText(text[i]).width / radius;}// 调整开始角度,使文本居中startAngle += (Math.PI - totalAngle) / 2;for (let i = 0; i < text.length; i++) {const char = text[i];const charWidth = ctx.measureText(char).width;const angle = startAngle + charWidth / (2 * radius);ctx.save();ctx.translate(x + Math.cos(angle) * radius, y + Math.sin(angle) * radius);ctx.rotate(angle + Math.PI / 2);ctx.fillText(char, -charWidth / 2, 0);ctx.restore();startAngle += charWidth / radius;}},
}}
使用的地方调用: this.generateStampImage();即可
生成的效果如下