跳转到主要内容

threejs使用canvas绘制文字

在threeejs中显示中文文字还是有点麻烦的,又是要自己转换字体等等巴拉巴,干脆直接用图片代替算了


/ 创建文本
function createText(text, fontSize) {

    const scale = 0.01;

    const canvas = document.createElement('canvas', { antialias: true });
    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;
    canvas.height = fontSize + 20;
    // 清除画布
    context.clearRect(0, 0, canvas.width, canvas.height);

    context.font = font;
    context.textAlign = 'center';
    context.textBaseline = 'middle';
    context.fillStyle = 'rgba(255, 0, 0, 1)';

    // 绘制文字
    context.fillText(text, canvas.width / 2, canvas.height / 2);

    // 创建纹理
    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;


    // const div = document.createElement('div');
    // div.className = 'label';
    // div.innerHTML = text;
    // // div.style.backgroundColor = 'rgba(255, 0, 0, 1)';
    // div.style.minWidth = 'auto';
    // div.style.fontSize = size + 'px';
    // const label = new CSS2DObject(div);
    // return label;

}