threejs sprite

Sprite is called sprite. In computer graphics, sprite refers to the two-dimensional image or animation contained in the scene. Mainly used for labels, because the front of the sprite model is always parallel to the canvas.

1 Use Sprite to create a 2D shape

Sprite is called sprite. In computer graphics, sprite refers to the two-dimensional image or animation contained in the scene. In threejs, you can use Sprite to load image textures. Of course, it also includes textures created with canvas. Therefore, what kind of image can be created by canvas, and what shape can be created by Sprite. The following example uses Sprite to create a circle:

function createSpriteShape(){
       /*1、创建一个画布,记得设置画布的宽高,否则将使用默认宽高,有可能会导致图像显示变形*/
        var canvas = document.createElement("canvas");
        canvas.width = 120;
        canvas.height = 120;
        /*2、创建图形,这部分可以去看w3c canvas教程*/
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = "#ff0000";
        ctx.arc(50,50,50,0,2*Math.PI);
        ctx.fill();
        /*3、将canvas作为纹理,创建Sprite*/
        var texture = new THREE.Texture(canvas);
        texture.needsUpdate = true; //注意这句不能少
        var material = new THREE.SpriteMaterial({map:texture});
        var mesh = new THREE.Sprite(material);
        /*4、放大图片,每个精灵有自己的大小,默认情况下都是很小的,如果你不放大,基本是看不到的*/
        mesh.scale.set(100,100,1);
        return mesh;
}


2 Use Sprite to create text

  

//先用画布将文字画出
            var canvas = document.createElement("canvas");
            var  ctx = canvas.getContext("2d");
            ctx.fillStyle = "#0000ff";
            ctx.font = "20px Arial";
            ctx.lineWidth = 1;
            ctx.fillText("ABCDRE",4,20);
            var texture = new THREE.Texture(canvas);
            texture.needsUpdate = true;

            //使用Sprite显示文字
            var material = new THREE.SpriteMaterial({map:texture});
            var textObj = new THREE.Sprite(material);
            textObj.scale.set(1,1,1);
            textObj.position.set(4,-4,1);
            scene.add(textObj);

3 Load texture image

//精灵对象Sprite
            var texture = new THREE.TextureLoader().load("test.png");
            // 创建精灵材质对象SpriteMaterial
            var spriteMaterial = new THREE.SpriteMaterial({
                    color:0xffffff,//设置精灵矩形区域颜色
                    //rotation:Math.PI/4,//旋转精灵对象45度,弧度值
                    map: texture,//设置精灵纹理贴图
                    transparent:true,
                });
            // 创建精灵模型对象,不需要几何体geometry参数
            var sprite = new THREE.Sprite(spriteMaterial);
            scene.add(sprite);
            // 控制精灵大小,比如可视化中精灵大小表征数据大小
            sprite.scale.set(0.5, 0.5, 1);  只需要设置x、y两个分量就可以
            sprite.position.set(0, -5, 1); 

Guess you like

Origin blog.csdn.net/sichuanpb/article/details/111151744