一、FontLoader
//option对象包含color,fontSize,position,rotate属性,可根据不同需求自行定义
addTextByFontLoader(option) {
var color = new THREE.Color(option.color);
let fontSize = option.fontSize;
var shapes = this.font.generateShapes(option.text, fontSize);
//绘制文字
var matLite = new THREE.MeshPhongMaterial({
color: option.color,
side: THREE.DoubleSide
});
var shapeGeometry = new THREE.ShapeGeometry(shapes);
shapeGeometry.computeBoundingBox();
var geometryText = new THREE.Mesh(shapeGeometry, matLite);
geometryText.position.set(option.position.x, option.position.y, option.position.z);
geometryText.rotateX(option.rotate.x || 0);
geometryText.rotateY(option.rotate.y || 0);
geometryText.rotateZ(option.rotate.z || 0);
this.scene.add(geometryText);
//添加文字描边效果
var matDark = new THREE.LineBasicMaterial({
color: 0xffffff,
side: THREE.DoubleSide
});
var holeShapes = [];
for (let i = 0; i < shapes.length; i++) {
const shape = shapes[i];
if (shape.holes && shape.holes.length > 0) {
for (let j = 0; j < shape.holes.length; j++) {
const hole = shape.holes[j];
holeShapes.push(hole);
}
}
}
shapes.push.apply(shapes, holeShapes);
var style = THREE.SVGLoader.getStrokeStyle(2, color.getStyle());
var strokeText = new THREE.Group();
for (let i = 0; i < shapes.length; i++) {
var shape = shapes[i];
var points = shape.getPoints();
var strokeGeometry = THREE.SVGLoader.pointsToStroke(points, style);
var strokeMesh = new THREE.Mesh(strokeGeometry, matDark);
strokeText.add(strokeMesh);
}
strokeText.position.set(option.position.x, option.position.y, option.position.z);
strokeText.rotateX(option.rotateX || 0);
strokeText.rotateY(option.rotateY || 0);
strokeText.rotateZ(option.rotateZ || 0);
this.scene.add(strokeText);
}
效果图:
二、CanvasTexture
drawByCanvasTexture(option) {
var canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
context.clearRect(0, 0, option.canvasWidth, option.canvasHeight);
context.fillStyle = 'rgba(44, 62, 80, 0)';
context.fillRect(0, 0, option.canvasWidth, option.canvasHeight);
context.textAlign = 'start';
context.font = 'Bold 20px Microsoft YaHei';
context.strokeStyle = 'rgba(255, 255, 255, 1.0)';
context.strokeText(option.text, 5, 20);
context.font = 'Bold 20px Microsoft YaHei';
context.fillStyle = 'rgb(51, 51, 51)';
context.fillText(option.text, 5, 20);
let texture = new THREE.CanvasTexture(canvas);
texture.needsUpdate = true;
let panel1 = new THREE.PlaneBufferGeometry(option.canvasWidth, option.canvasHeight);
let panelMate1 = new THREE.MeshBasicMaterial({
map: texture,
transparent: true,
side: THREE.DoubleSide
});
let panelMesh = new THREE.Mesh(panel1, panelMate1);
panelMesh.position.set(option.position.x, option.position.y, option.position.z);
panelMesh.rotateX(option.rotate.x);
panelMesh.rotateZ(option.rotate.y);
this.scene.add(panelMesh);
}
效果图: