Photo credit: unsplash.com/photos/xyhR…

We are committed to building the first “cloud CAD” collaborative design platform integrating viewing, modeling, assembly and rendering in China.

The Sprite is a plane that is always facing the camera. It has no concept of a Z-axis. It is usually used to load textures and is used as a label. So we can use it to display some tags, and when we change the viewing Angle, the tags change the Angle. In computer graphics, Sprite refers to a two-dimensional image or animation contained in the scene. The base class is Object3D. The methods and properties of the Sprite model object can be viewed in addition to the document Sprite, but also the base class Object3D.

Create the basic components

As mentioned earlier, a three.js scenario must contain some necessary components. Scenes, cameras, renderers, etc. The following code initializes some basic components for reuse

 function initScence() {
            var scene = new THREE.Scene();
            / / linear light
            var directionalLight = new THREE.DirectionalLight(0xffffff.0.7);
            directionalLight.position.set(-20.40.60);
            scene.add(directionalLight);
            / / the ambient light
            var ambientLight = new THREE.AmbientLight(0x292929);
            scene.add(ambientLight);
            return scene
        }

        function initCamera() {
            var camera = new THREE.PerspectiveCamera(45.window.innerWidth / window.innerHeight, 0.1.1000);
            camera.position.x = 120;
            camera.position.y = 60;
            camera.position.z = 180;
            return camera
        }

        function initRender() {
            var renderer = new THREE.WebGLRenderer();
            renderer.setClearColor(new THREE.Color(0xEEEEEE.1.0));
            renderer.setSize(window.innerWidth, window.innerHeight);
            return renderer
        }
        
        function init() {
      
            var scene = initScence();
            var camera = initCamera();
            var renderer = initRender()
            camera.lookAt(scene.position);

            // Add the element TODO from the scene

           
            document.getElementById("WebGL-output").appendChild(renderer.domElement);
            render();
            function render() { requestAnimationFrame(render); renderer.render(scene, camera); }}window.onload = init
Copy the code

Use Sprite to create 2D shapes

You don’t need geometry to create a Sprite model. You just need to set the Sprite constructor parameter to a Sprite material SpriteMaterial.

Like ordinary mesh materials, SpriteMaterial allows you to set color,.map,.transparent,.opacity, and other properties. The base class of the SpriteMaterial is Material.

In addition to the properties and methods that are similar to the mesh material, SpriteMaterial has its own unique properties, such as the.Rotation Sprite model. For more properties and methods, see the Threejs documentation for SpriteMaterial.

In Threejs, you can use Sprite to load image textures, as well as textures created with the Canvas, so that the canvas can create any image, and the Sprite can create any shape. The following example creates a circle using Sprite:

function createSpriteShape(){
       /*1, create a canvas, remember to set the canvas width and height, otherwise the default width and height will be used, may cause the image display distortion */
        let canvas = document.createElement("canvas");
        canvas.width = 120;
        canvas.height = 120;
        /*2, create a graphic, see the W3C Canvas tutorial */ for this part
        let ctx = canvas.getContext("2d");
        ctx.fillStyle = "#ff0000";
        ctx.arc(50.50.50.0.2*Math.PI);
        ctx.fill();
        /* create Sprite*/ with canvas as the texture
        let texture = new THREE.Texture(canvas);
        texture.needsUpdate = true; // Pay attention to this sentence
        let material =  new THREE.SpriteMaterial({
          color:0xff00ff.// Set the color of the Sprite rectangle
          rotation:Math.PI/4.// Rotate the Sprite object by 45 degrees, radian value
          map: texture,// Set Sprite texture map
        });
        let mesh = new THREE.Sprite(material);
        Each Sprite has its own size. By default, the Sprite is very small. If you do not zoom in, it will be almost invisible
        / / mesh. Scale. The set (100100, 1);
        return mesh;
}
Copy the code

Then add the mesh to the scence and you can just see the effect

function init() {
            var scene = initScence();
            var camera = initCamera();
            var renderer = initRender()
            camera.lookAt(scene.position);
            scene.add(createSpriteShape())
            
            document.getElementById("WebGL-output").appendChild(renderer.domElement);
            render();
            function render() { requestAnimationFrame(render); renderer.render(scene, camera); }}Copy the code

Scale and position

Natural Sprite models also have a scale property and a position property. Generally, the Sprite model size is set by the.scale property, and the Sprite model position is set by the.position property. The Sprite model can change its position in the 3D scene just like a normal model. The difference is that the front of the Sprite model is always parallel to the canvas.

When using perspective projection camera objects, the size of the Sprite model objects is affected by the same distance as the mesh model, i.e. the farther away the Sprite object is, the smaller the display effect is.

Use Sprite to create text

function createSpriteText(){
        // Use the canvas to draw the text
        let canvas = document.createElement("canvas");
        let ctx = canvas.getContext("2d");
        ctx.fillStyle = "#ffff00";
        ctx.font = "Bold 100px Arial";
        ctx.lineWidth = 4;
        ctx.fillText("Hello World".4.104);
        let texture = new THREE.Texture(canvas);
        texture.needsUpdate = true;
        
        // Use Sprite to display text
        let material = new THREE.SpriteMaterial({map:texture});
        let textObj = new THREE.Sprite(material);
        textObj.scale.set(0.5 * 100.0.25 * 100.0.75 * 100);
        textObj.position.set(0.0.98);
        return textObj;
}
Copy the code

And then you add textObj to your scence and you just see the effect

  // once everything is loaded, we run our Three.js stuff.
        function init() {
            var stats = initStats();
            var scene = initScence();
            var camera = initCamera();
            var renderer = initRender()
            camera.lookAt(scene.position);

            // scene.add(createSpriteShape())
            scene.add(createSpriteText())
            document.getElementById("WebGL-output").appendChild(renderer.domElement);
            render();
            function render() { stats.update(); requestAnimationFrame(render); renderer.render(scene, camera); }}window.onload = init

Copy the code

Write in the last

This article introduces the Sprite related content of three.js, including the use of Sprite to create 2D shapes and create text, hope to help you.

This article is published from yuntu 3D big front end team. Any unauthorized reprint of the article is prohibited.