threejs使用canvas绘制文字
在threeejs中显示中文文字还是有点麻烦的,又是要自己转换字体等等巴拉巴,干脆直接用图片代替算了
// 创建文本
function createText(text, fontSize) {
const scale = 0.01;
let textLines = text.split("\n");
if (textLines.length > 1) {
let textLine2 = textLines[1];
textLines.splice(1, 1); // 删除原来的元素
for (let i = 0; i < textLine2.length; i += 7) {
textLines.push(textLine2.substr(i, 7));
}
}
currentCanvas.value = document.createElement("canvas", { antialias: true });
const canvas = currentCanvas.value;
const context = canvas.getContext("2d");
context.imageSmoothingEnabled = true;
context.imageSmoothingQuality = "high";
// 创建2X图以提高文字的清晰度
const font = fontSize * 2 + "px Arial";
context.font = font;
// 计算文字的宽度
const textMetrics = context.measureText(text);
canvas.width = textMetrics.width + 20;
let textLineHeight = fontSize * 2 * 1.2; // 行高约为字体的1.2倍
canvas.height = textLineHeight * (textLines.length + 1); // 计算有多少行
// 清除画布
context.clearRect(0, 0, canvas.width, canvas.height);
context.font = font;
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = "rgba(255,255, 255, 1)";
let textY = textLineHeight;
context.fillText(textLines[0], canvas.width / 2, textY);
context.fillStyle = "rgba(255,255, 255, 1)";
// 每行显示7个字符
for (let i = 1; i < textLines.length; i++) {
textY += textLineHeight;
context.fillText(textLines[i], canvas.width / 2, textY);
}
// 创建纹理
const texture = new THREE.CanvasTexture(canvas);
texture.needsUpdate = true;
// 创建几何体和材质
const geometry = new THREE.PlaneGeometry((canvas.width / 2) * scale, (canvas.height / 2) * scale);
const material = new THREE.MeshBasicMaterial({ map: texture, opacity: 1, transparent: true });
// 创建网格
const mesh = new THREE.Mesh(geometry, material);
return mesh;
}