注释标记了操作步骤:
import React, { Component, createRef } from 'react';
class CertifyImgRender extends Component {
$bgRef = createRef<HTMLCanvasElement>()
$textRef = createRef<HTMLCanvasElement>()
async renderImage() {
const img = new Image()
img.crossOrigin = "anonymous";
const canvas = this.$bgRef.current;
const ctx = canvas.getContext('2d');
img.onload = async () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
//1.绘制文字样式
ctx.font = "bold 36px Arial";
ctx.fillStyle = "black";
let name = "Abbbb,aeee aaaaaaa aaaaa aaaaaaaa"
let name2 = "尼古拉"
//2.一般英文为16个字符换行 中文为四个字符
const maxLength = 4;
let formattedName = '';
let index = 0;
const lineHeight = 36; // 由于字号为36所以行高设为36
//3.拼接换行符
while (index < name2.length) {
formattedName += name2.slice(index, index + maxLength) + '\n';
index += maxLength;
}
// 4.根据换行符分割文字为多行
const words = formattedName.split('\n');
let y = 396;
//5,换行打印
words.forEach((line) => {
ctx.fillText(line, 350, y);
y += lineHeight;
})
// 6.将Canvas内容转换为Blob对象
canvas.toBlob(function (blob) {
var file = new File([blob], "image_with_text.png", { type: blob.type });
// 发送给后端
console.log("file",file)
}, "image/jpeg");
}
//替换为真实的图片路径
img.src = "放需要加文字的图片地址"
}
componentDidMount() {
// console.log(this.props)
this.renderImage()
}
componentDidUpdate() {
this.renderImage()
}
render() {
return (
<div data-rrr>
<canvas ref={this.$bgRef} style={{ width: "100%", height: "100%" }} />
</div>
)
}
}
export default CertifyImgRender