three.js简易教程

three.js(16)-精灵图

2021-12-01  本文已影响0人  姜治宇

Sprite精灵图是指场景中的二维图像。
这种图是永远面向相机的平面,通常用来加载纹理。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="http://www.yanhuangxueyuan.com/versions/threejsR92/build/three.js"></script>
    <script src="http://www.yanhuangxueyuan.com/threejs/examples/js/controls/OrbitControls.js"></script>
    <script src="http://www.yanhuangxueyuan.com/threejs/examples/js/loaders/GLTFLoader.js"></script>
    <title>Document</title>
</head>

<body>
    <div id="webgl"></div>
</body>

</html>
<script>
    var scene = new THREE.Scene();
    var axes = new THREE.AxesHelper(50);//添加辅助坐标系
    scene.add(axes);
    //================================地面================================================//
    var plane = new THREE.PlaneGeometry(150, 50);
    var materialPlane = new THREE.MeshBasicMaterial({
        color: 0xcccccc
    });
    var planeMesh = new THREE.Mesh(plane, materialPlane);
    planeMesh.rotation.x = -0.5 * Math.PI; //沿x轴翻转90°,即为展平效果
    planeMesh.position.set(0, 0, 0);

    scene.add(planeMesh);
    //====================精灵图(canvas)=================//
    scene.add(createSprite(getCanvas()));

    //=============================相机=============================================//
    var camera = new THREE.PerspectiveCamera(45, 2, 0.1, 2000);
    camera.position.set(10, 10, 10);
    camera.lookAt(scene.position);


    /**
     * 创建渲染器对象
     */
    var renderer = new THREE.WebGLRenderer({
        antialias: true //消除锯齿
    });

    renderer.setSize(1000, 500);
    renderer.setClearColor(0xb9d3ff, 1);

    renderer.render(scene, camera);
    var cont = document.getElementById('webgl');
    cont.appendChild(renderer.domElement);

    //增加鼠标拾取效果
    var controls = new THREE.OrbitControls(camera, renderer.domElement);
    controls.addEventListener('change', () => {
        renderer.render(scene, camera);
    });

    function createSprite(canvas){
        let texture =new THREE.Texture(canvas);
        texture.needsUpdate = true;
        let material = new THREE.SpriteMaterial({
            map:texture
        });
        let mesh = new THREE.Sprite(material);
        mesh.position.set(0,2,0);
        return mesh;

    }
    function getCanvas(){
        let canvas = document.createElement('canvas');
        canvas.width = 200;
        canvas.height = 200;
        let ctx = canvas.getContext('2d');
        ctx.fillStyle = '#ff0000';
        ctx.arc(100,100,100,0,2*Math.PI);//画圆
        ctx.fill();
        ctx.fillStyle = "#ffff00";
        ctx.font = "Bold 100px Arial";
        ctx.fillText("你好",0,120);//写字
        return canvas;
    }

</script>
canvas.gif
上一篇 下一篇

猜你喜欢

热点阅读