three.js 文本_使用Three-bmfont-text在Three.js中创建文本
three.js 文本
There are many ways of displaying text inside a Three.js application: drawing text to a canvas and use it as a texture, importing a 3D model of a text, creating text geometry, and using bitmap fonts — or BMFonts. This last one has a bunch of helpful properties on how to render text into a scene.
在Three.js應用程序內顯示文本的方法有很多:將文本繪制到畫布上并將其用作紋理,導入文本的3D模型,創建文本幾何圖形以及使用位圖字體(或BMFonts)。 最后一個關于如何將文本渲染到場景中的一堆有用的屬性。
Text in WebGL opens many possibilities to create amazing things on the web. A great example is Sorry, Not Sorry by awesome folks at Resn or this refraction experiment by Jesper Vos. Let’s use Three.js with three-bmfont-text to create text in 3D and give it a nice look using shaders.
WebGL中的文本為在網絡上創建驚人的事物提供了許多可能性。 一個很好的例子是Resn的優秀人員對不起,而不是對不起,或者Jesper Vos進行的折射實驗。 讓我們將Three.js與three-bmfont-text一起使用,以3D格式創建文本,并使用著色器為其提供漂亮外觀。
Three-bmfont-text is a tool created by Matt DesLauriers and Jam3 that renders BMFont files in Three.js, allowing to batch glyphs into a single geometry. It also supports things like word-wrapping, kerning, and msdf — please watch Zach Tellman’s talk on distance fields, he explains it very good.
Three-bmfont-text是由Matt DesLauriers和Jam3創建的工具,用于在Three.js中呈現BMFont文件,從而可以將字形批量化為單個幾何體。 它還支持自動換行,字距調整和msdf等功能-請觀看Zach Tellman在距離場上的演講,他解釋得很好。
With all that said, let’s begin.
綜上所述,讓我們開始吧。
Attention: This tutorial assumes you have some understanding of 注意:本教程假定您對Three.js, GLSL shaders and Three.js ,GLSL著色器和glslify, so we’ll skip things like glslify有所了解,因此我們將跳過諸如how to set up a scene and import shaders.設置場景和導入著色器之類的操作。入門 (Getting started)
Before everything, we need to load a font file to create a geometry three-bmfont-text provides packed with bitmap glyphs. Then, we load a texture atlas of the font which is a collection of all characters inside a single image. After loading is done, we’ll pass the geometry and material to a function that will initialize a Three.js setup. To generate these files check out this repository.
在開始之前,我們需要加載一個字體文件來創建一個幾何圖形,三個bmfont-text提供了位圖字形。 然后,我們加載字體的紋理圖集,該紋理圖集是單個圖像內所有字符的集合。 加載完成后,我們會將幾何圖形和材質傳遞給一個函數,該函數將初始化Three.js設置。 要生成這些文件,請簽出該存儲庫。
const createGeometry = require('three-bmfont-text'); const loadFont = require('load-bmfont');loadFont('fonts/Lato.fnt', (err, font) => {// Create a geometry of packed bitmap glyphsconst geometry = createGeometry({font,text: 'OCEAN'});// Load texture containing font glyphsconst loader = new THREE.TextureLoader();loader.load('fonts/Lato.png', (texture) => {// Start and animate rendererinit(geometry, texture);animate();}); });創建文本網格 (Creating the text mesh)
It’s time to create the mesh with the msdf shader three-bmfont-text comes with. This module has a default vertex and fragment shader that forms sharp text. We’ll change them later to produce a wavy effect.
是時候使用附帶的msdf著色器創建3bmfont-text了。 該模塊具有默認的頂點和片段著色器,可形成清晰的文本。 稍后我們將對其進行更改以產生波浪效果。
const MSDFShader = require('three-bmfont-text/shaders/msdf');function init(geometry, texture) {// Create material with msdf shader from three-bmfont-textconst material = new THREE.RawShaderMaterial(MSDFShader({map: texture,color: 0x000000, // We'll remove it later when defining the fragment shaderside: THREE.DoubleSide,transparent: true,negate: false,}));// Create mesh of text const mesh = new THREE.Mesh(geometry, material);mesh.position.set(-80, 0, 0); // Move according to text sizemesh.rotation.set(Math.PI, 0, 0); // Spin to face correctlyscene.add(mesh); }And now the text should appear on screen. Cool, right? You can zoom and rotate with the mouse to see how crisp the text is.
現在文本應該出現在屏幕上。 酷吧? 您可以使用鼠標縮放和旋轉以查看文本的清晰度。
演示地址
Let’s make it more interesting in the next step.
讓我們在下一步變得更有趣。
GLSL (GLSL)
頂點著色器 (Vertex shader)
To oscillate the text, trigonometry is our best friend. We want to make a sinusoidal movement along the Y and Z axis — up and down, inside and outside the screen. A vertex shader fits the bill for this since it handles the position of the vertices of the mesh. But before this, let’s add the shaders to the material and create a time uniform that will fuel them.
為了使文本振蕩,三角函數是我們最好的朋友。 我們希望沿著Y和Z軸(在屏幕的內部和外部)上下進行正弦運動。 頂點著色器適合此目的,因為它可以處理網格頂點的位置。 但是在此之前,讓我們將著色器添加到材質中,并創建一個將為其加油的時間均勻性。
function init(geometry, texture) {// Create material with msdf shader from three-bmfont-textconst material = new THREE.RawShaderMaterial(MSDFShader({vertexShader,fragmentShader,map: texture,side: THREE.DoubleSide,transparent: true,negate: false,}));// Create time uniform from default uniforms objectmaterial.uniforms.time = { type: 'f', value: 0.0 }; }function animate() {requestAnimationFrame(animate);render(); }function render() {// Update time uniform each framemesh.material.uniforms.time.value = this.clock.getElapsedTime();mesh.material.uniformsNeedUpdate = true;renderer.render(scene, camera); }Then we’ll pass it to the vertex shader:
然后,將其傳遞給頂點著色器:
// Variable qualifiers that come with the msdf shader attribute vec2 uv; attribute vec4 position; uniform mat4 projectionMatrix; uniform mat4 modelViewMatrix; varying vec2 vUv; // We passed this one uniform float time;void main() {vUv = uv;vec3 p = vec3(position.x, position.y, position.z);float frequency1 = 0.035;float amplitude1 = 20.0;float frequency2 = 0.025;float amplitude2 = 70.0;// Oscillate vertices up/downp.y += (sin(p.x * frequency1 + time) * 0.5 + 0.5) * amplitude1;// Oscillate vertices inside/outsidep.z += (sin(p.x * frequency2 + time) * 0.5 + 0.5) * amplitude2;gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0); }Frequency and amplitude are properties of a wave that determine their quantity and their “height”. Because we are using a sine wave to move the vertices, these properties can help control the behavior of the wave. I encourage you to tweak the values to observe different results.
頻率和振幅是決定其數量和“高度”的波的屬性。 因為我們使用正弦波移動頂點,所以這些屬性可以幫助控制波的行為。 我鼓勵您調整值以觀察不同的結果。
Okay, so here is the tidal movement:
好的,這是潮汐運動:
演示地址
片段著色器(Fragment shader)
For the fragment shader, I thought about just interpolating between two shades of blue – a light and a dark one. Simple as that.
對于片段著色器,我考慮過僅在兩種藍色陰影之間進行插值-淺色和深色。 就那么簡單。
The built-in GLSL function mix helps interpolating between two values. We can use it along with a cosine function mapped from 1 to 0, so it can go back and forth these values and change the color of the text — a value of 1 will give a dark blue and 0 a light blue, interpolating the colors between.
內置的GLSL函數混合有助于在兩個值之間進行插值。 我們可以將其與從1到0映射的余弦函數一起使用,因此它可以來回移動這些值并更改文本的顏色-值1表示深藍色,0表示淺藍色,對顏色進行插值之間。
#ifdef GL_OES_standard_derivatives #extension GL_OES_standard_derivatives : enable #endif// Variable qualifiers that come with the shader precision highp float; uniform float opacity; uniform vec3 color; uniform sampler2D map; varying vec2 vUv; // We passed this one uniform float time;// HSL to RGB color conversion module #pragma glslify: hsl2rgb = require(glsl-hsl2rgb)float median(float r, float g, float b) {return max(min(r, g), min(max(r, g), b)); }void main() {// This is the code that comes to produce msdfvec3 sample = texture2D(map, vUv).rgb;float sigDist = median(sample.r, sample.g, sample.b) - 0.5;float alpha = clamp(sigDist/fwidth(sigDist) + 0.5, 0.0, 1.0);// Colorsvec3 lightBlue = hsl2rgb(202.0 / 360.0, 1.0, 0.5);vec3 navyBlue = hsl2rgb(238.0 / 360.0, 0.47, 0.31);// Goes from 1.0 to 0.0 and vice versafloat t = cos(time) * 0.5 + 0.5;// Interpolate from light to navy bluevec3 newColor = mix(lightBlue, navyBlue, t);gl_FragColor = vec4(newColor, alpha * opacity);if (gl_FragColor.a < 0.0001) discard; }And here it is! The final result:
在這里! 最終結果:
演示地址
其他例子(Other examples)
There is plenty of stuff one can do with three-bmfont-text. You can make words fall:
三bmfont文本可以做很多事情。 您可以使單詞掉落:
演示地址
Enter and leave:
進入并離開:
演示地址
Distortion:
失真:
演示地址
Water blend:
水混合:
演示地址
Or mess with noise:
或雜亂無章:
演示地址
I encourage you to explore more to create something that gets you excited, and please share it with me via twitter or email. You can reach me there, too if you got any questions, or comment below.
我鼓勵您探索更多內容,以創建讓您興奮的東西,并通過Twitter或電子郵件與我分享。 如果您有任何疑問或在下面發表評論,也可以在這里與我聯系。
Hope you learned something new. Cheers!
希望你學到新東西。 干杯!
參考和鳴謝 (References and Credits)
Three.js
Three.js
three-bmfont-text
三字體字體文本
Glslify
Glslify
Author of msdf
msdf的作者
Generator for msdf files
msdf文件的生成器
The Book of Shaders
著色書
翻譯自: https://tympanus.net/codrops/2019/10/10/create-text-in-three-js-with-three-bmfont-text/
three.js 文本
總結
以上是生活随笔為你收集整理的three.js 文本_使用Three-bmfont-text在Three.js中创建文本的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: cocos2d-x 使用BMFont生成
- 下一篇: bmfont-instructions