如何在three.js中将文本混合到纹理上?

4
我想在一罐豆子上添加文本。这个示例代码使用render.copyTextureToTexture来混合纹理。
然而,当我尝试使用它时,它没有任何效果。
当我尝试在圆柱体上显示textTexture时,它完全透明。这个纹理是在第一个画布中呈现文本之前创建的吗?
或者我需要以某种方式等待图像加载完成,然后再使用copyTextureToTexture添加文本吗?

//import * as THREE from 'https://threejs.org/build/three.module.js';

const ctx = document.getElementById('textCanvas').getContext('2d');
ctx.font = '2em Lucida Sans Unicode';
ctx.fillText('Text to be added', 0, 75, 500);

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, 4 / 3, 0.1, 1000);

var renderer = new THREE.WebGLRenderer({
  alpha: true
});
renderer.setSize(320, 240);
document.body.appendChild(renderer.domElement);

var img1 = "https://i.imgur.com/IIToHlc.png";

var texture1 = new THREE.TextureLoader().load(img1);

textTexture = new THREE.CanvasTexture(document.getElementById('textCanvas'));

const position = new THREE.Vector2();
position.x = 1;
position.y = 1;
renderer.copyTextureToTexture(position, textTexture, texture1);

const geometry = new THREE.CylinderGeometry(5, 5, 12, 32);
const material = [
  new THREE.MeshLambertMaterial({
    map: texture1
  }),
  new THREE.MeshLambertMaterial({
    color: 0x5f5f5f
  }),
  new THREE.MeshLambertMaterial({
    color: 0x5f5f7f
  })
]

const cylinder = new THREE.Mesh(geometry, material);
scene.add(cylinder);

const light = new THREE.AmbientLight(0x404040); // soft white light
scene.add(light);

var directionalLight = new THREE.DirectionalLight(0xafafaf, 1);
directionalLight.position.z = 1;
directionalLight.position.x = -0.5;
directionalLight.position.y = 0.2;

scene.add(directionalLight);

camera.position.z = 15;
camera.position.y = 0;

var zRotation = -0.005;
var maxZRotation = 0.5;
cylinder.rotation.z = maxZRotation;

var animate = function() {
  requestAnimationFrame(animate);

  cylinder.rotation.y += -0.02;
  cylinder.rotation.z += zRotation;

  if (cylinder.rotation.z >= maxZRotation) {
    zRotation = -0.005;
  }
  if (cylinder.rotation.z <= -maxZRotation) {
    zRotation = 0.005;
  }
  renderer.render(scene, camera);
};
animate();
body {
  margin: 0;
  overflow: hidden;
  background-color: rgba(0, 0, 0, 0);
}

canvas {
  background-color: rgba(0, 0, 0, 0);
}
<!DOCTYPE html>
<html>

<head>
  <title>Floating can of BEANS</title>
</head>

<body>
  <canvas id="textCanvas" width="500" height="150" style="height:150px; width:500px; position: absolute; top: 512px; "></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
</body>

1个回答

2
你可以修改材质,使其能够将材质的颜色与文本纹理混合:

enter image description here

body{
  overflow: hidden;
  margin: 0;
}
<script type="module">
import * as THREE from "https://cdn.skypack.dev/three@0.136.0";
import {
  OrbitControls
} from "https://cdn.skypack.dev/three@0.136.0/examples/jsm/controls/OrbitControls";

let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 1000);
camera.position.set(0, 3, 8);
let renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(innerWidth, innerHeight);
//renderer.setClearColor(0xffffff)
document.body.appendChild(renderer.domElement);
window.addEventListener("resize", event => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(innerWidth, innerHeight);
})

let controls = new OrbitControls(camera, renderer.domElement);

let light = new THREE.DirectionalLight(0xffffff, 1);
light.position.setScalar(1);
scene.add(light, new THREE.AmbientLight(0xffffff, 0.25));

let c = document.createElement("canvas");
c.width = 256;
c.height = 128;
let ctx = c.getContext("2d");
ctx.fillStyle = "rgba(255, 255, 255, 0)";
ctx.fillRect(0, 0, c.width, c.height);
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "magenta";
ctx.font = "bold 36px Arial";
let text = "I love Three.js";
ctx.fillText(text, c.width * 0.5, c.height * 0.5);
ctx.strokeStyle = "red";
ctx.strokeText(text, c.width * 0.5, c.height * 0.5);
let tex = new THREE.CanvasTexture(c);
tex.offset.y = 0.25;

let u = {
    time: {value: 0},
    textTex: {value: tex}
}


let g = new THREE.CylinderGeometry(2, 2, 4.5, 36, 1, true);
g.rotateY(Math.PI);
let m = new THREE.MeshLambertMaterial({
    color: 0x7f7f64,
  map: new THREE.TextureLoader().load("https://threejs.org/examples/textures/floors/FloorsCheckerboard_S_Diffuse.jpg", tex => {
    tex.wrapS = THREE.RepeatWrapping;
    tex.wrapT = THREE.RepeatWrapping;
    tex.repeat.set( 3, 1 );
  }),
  side: THREE.DoubleSide,
  onBeforeCompile: shader => {
    shader.uniforms.time = u.time;
    shader.uniforms.textTex = u.textTex;
    shader.fragmentShader = `
        uniform float time;
        uniform sampler2D textTex;
      ${shader.fragmentShader}
    `.replace(
        `#include <map_fragment>`,
      `#include <map_fragment>
      
        vec4 textCol = texture(textTex, (vUv * 2. - 0.5) + vec2(-2., sin(time) * 0.25));
        vec3 col = mix(diffuseColor.rgb, textCol.rgb, textCol.a);
        diffuseColor = vec4( col, opacity );
      `
    );
    //console.log(shader.fragmentShader);
  }
});
m.defines = {"USE_UV" : ""};
let o = new THREE.Mesh(g, m);
scene.add(o);

let clock = new THREE.Clock();

renderer.setAnimationLoop(() => {

  let time = clock.getElapsedTime();
  u.time.value = time;
  renderer.render(scene, camera);
});

</script>


谢谢您。对我来说,添加着色器似乎有点太复杂了。最终我将图像添加到画布中,并在其上绘制文本。 - Raukgorth
@Raukgorth 是的,那也是一个选项 :) - prisoner849
请注意,copyTextureToTexture函数会_替换_ dstImage 中的像素。因此,如果您的整个图像是0xff0000ff(不透明的红色),并且您复制了一个完全由0x0000ff80(蓝色,50%透明)组成的纹理,则会得到一个完全由0x0000ff80(蓝色,50%透明)组成的纹理。您将无法获得混合后的图像(0xff0080ff,实心粉色),这正是您要寻找的效果。要进行混合,您必须在画布中(就像您所做的那样),在着色器中(就像@prisoner849所做的那样)或通过其他方法来合成该图像。 - Phil N.
谢谢@prisoner849。我已经为自己的用例实施了这个功能:在均匀着色的表面上不移动的文本(color: 0xF7DD51, map: tex, => 没有纹理)。我的文本被显示出来,但是当没有实现着色器时,文本颜色与material.color混合(如前面的评论所述)。但是当我尝试按照这里描述的方法实现着色器时,表面颜色不再显示,文本背景变成了黑色。我已经尝试了六个小时,但没有成功。我需要在我的着色器定义中做哪些改变? - Skratt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接