99 Three.js使用canvas更新纹理

这里写图片描述

案例查看地址:http://www.wjceo.com/blog/threejs/2018-05-10/162.html

简介

Three.js可以直接将canvas画布上的图像作为纹理绘制到模型上面。下面我们说一下如何实现

案例实现

  • 首先,我们创建了一个canvas对象,并使用js在上面循环绘制图像。在上面绘制了一个火在燃烧的动画。
<canvas id="surface"></canvas>
  • 然后我们获取到canvas的dom对象,通过dom对象实例化一个texture对象:
//获取到canvas对象
var canvas = $("#surface")[0];
//通过canvas对象实例化纹理
var texture = new THREE.Texture(canvas);
material = new THREE.MeshBasicMaterial( { map: texture } );
  • 然后通过这个材质创建模型放到场景当中,即可完成了使用canvas
  • 最后,如果canvas的内容变动了,如何更新材质呢?可以直接设置texture更新即可:
material.map.needsUpdate = true;

案例代码


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Threejs使用canvas更新纹理</title>
    <style type="text/css">
        html, body {
            margin: 0;
            height: 100%;
        }

        canvas {
            display: block;
        }

        #surface{
            position: fixed;
            left:0;
            bottom:0;
        }
    </style>
</head>

<body onload="draw();">
<canvas id="surface"></canvas>
</body>
<script src="https://cdn.bootcss.com/three.js/91/three.min.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="/lib/js/controls/OrbitControls.js"></script>
<script src="https://cdn.bootcss.com/stats.js/r17/Stats.min.js"></script>
<script src="https://cdn.bootcss.com/dat-gui/0.7.1/dat.gui.min.js"></script>
<script src="/lib/js/Detector.js"></script>

<script>
    var renderer, camera, scene, gui, light, stats, controls;

    //引入一个canvas动画
    function initCanvas() {
        $( document ).ready(function() {

            // Set canvas drawing surface
            var space = document.getElementById("surface");
            var surface = space.getContext("2d");
            surface.scale(1,1);

            // Set Particles
            var particles = [];
            var particle_count = 150;
            for(var i = 0; i < particle_count; i++) {
                particles.push(new particle());
            }
            var time = 0;
            // Set wrapper and canvas items size
            var canvasWidth=480;
            var canvasHeight=480;
            $(".wrapper").css({width:canvasWidth,height:canvasHeight});
            $("#surface").css({width:canvasWidth,height:canvasHeight});

            // shim layer with setTimeout fallback from Paul Irish
            window.requestAnimFrame = (function(){
                return  window.requestAnimationFrame       ||
                    window.webkitRequestAnimationFrame ||
                    window.mozRequestAnimationFrame    ||
                    function( callback ){
                        window.setTimeout(callback, 6000 / 60);
                    };
            })();

            function particle() {

                this.speed = {x: -1+Math.random()*2, y: -5+Math.random()*5};
                canvasWidth = (document.getElementById("surface").width);
                canvasHeight= (document.getElementById("surface").height);
                this.location = {x: canvasWidth/2, y: (canvasHeight/2)+35};

                this.radius = .5+Math.random()*1;

                this.life = 10+Math.random()*10;
                this.death = this.life;

                this.r = 255;
                this.g = Math.round(Math.random()*155);
                this.b = 0;
            }

            function ParticleAnimation(){
                surface.globalCompositeOperation = "source-over";
                surface.fillStyle = "black";
                surface.fillRect(0, 0, canvasWidth, canvasHeight);
                surface.globalCompositeOperation = "lighter";

                for(var i = 0; i < particles.length; i++)
                {
                    var p = particles[i];

                    surface.beginPath();

                    p.opacity = Math.round(p.death/p.life*100)/100
                    var gradient = surface.createRadialGradient(p.location.x, p.location.y, 0, p.location.x, p.location.y, p.radius);
                    gradient.addColorStop(0, "rgba("+p.r+", "+p.g+", "+p.b+", "+p.opacity+")");
                    gradient.addColorStop(0.5, "rgba("+p.r+", "+p.g+", "+p.b+", "+p.opacity+")");
                    gradient.addColorStop(1, "rgba("+p.r+", "+p.g+", "+p.b+", 0)");
                    surface.fillStyle = gradient;
                    surface.arc(p.location.x, p.location.y, p.radius, Math.PI*2, false);
                    surface.fill();
                    p.death--;
                    p.radius++;
                    p.location.x += (p.speed.x);
                    p.location.y += (p.speed.y);

                    //regenerate particles
                    if(p.death < 0 || p.radius < 0){
                        //a brand new particle replacing the dead one
                        particles[i] = new particle();
                    }
                }



                requestAnimFrame(ParticleAnimation);

            }

            ParticleAnimation();

        });
    }

    function initRender() {
        renderer = new THREE.WebGLRenderer({antialias: true});
        renderer.setPixelRatio(window.devicePixelRatio);
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.setClearColor(0xeeeeee);
        renderer.shadowMap.enabled = true;
        //告诉渲染器需要阴影效果
        document.body.appendChild(renderer.domElement);
    }

    function initCamera() {
        camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
        camera.position.set(0, 0, 15 );
    }

    function initScene() {
        //给场景添加天空盒子纹理
        var cubeTextureLoader = new THREE.CubeTextureLoader();
        cubeTextureLoader.setPath( '/lib/textures/cube/space/' );
        //六张图片分别是朝前的(posz)、朝后的(negz)、朝上的(posy)、朝下的(negy)、朝右的(posx)和朝左的(negx)。
        var cubeTexture = cubeTextureLoader.load( [
            'right.jpg', 'left.jpg',
            'top.jpg', 'bottom.jpg',
            'front.jpg', 'back.jpg'
        ] );

        scene = new THREE.Scene();

        scene.background = cubeTexture;
    }

    //初始化dat.GUI简化试验流程
    function initGui() {
        //声明一个保存需求修改的相关数据的对象
        gui = {
        };
        var datGui = new dat.GUI();
        //将设置属性添加到gui当中,gui.add(对象,属性,最小值,最大值)
    }

    function initLight() {
        scene.add(new THREE.AmbientLight(0x444444));

        light = new THREE.DirectionalLight(0xffffff);
        light.position.set(0, 20, 20 );

        light.castShadow = true;
        light.shadow.camera.top = 10;
        light.shadow.camera.bottom = -10;
        light.shadow.camera.left = -10;
        light.shadow.camera.right = 10;

        //告诉平行光需要开启阴影投射
        light.castShadow = true;

        scene.add(light);
    }

    function initModel() {

        //辅助工具
        var helper = new THREE.AxesHelper(50);
        scene.add(helper);

        //添加立方体
        var geometry = new THREE.BoxBufferGeometry( 5, 5, 5 );

        //获取到canvas对象
        var canvas = $("#surface")[0];
        //通过canvas对象实例化纹理
        var texture = new THREE.Texture(canvas);
        material = new THREE.MeshBasicMaterial( { map: texture } );

        scene.add(new THREE.Mesh(geometry, material));
    }

    //初始化性能插件
    function initStats() {
        stats = new Stats();
        document.body.appendChild(stats.dom);
    }

    function initControls() {

        controls = new THREE.OrbitControls(camera, renderer.domElement);
        //设置控制器的中心点
        //controls.target.set( 0, 5, 0 );
        // 如果使用animate方法时,将此函数删除
        //controls.addEventListener( 'change', render );
        // 使动画循环使用时阻尼或自转 意思是否有惯性
        controls.enableDamping = true;
        //动态阻尼系数 就是鼠标拖拽旋转灵敏度
        //controls.dampingFactor = 0.25;
        //是否可以缩放
        controls.enableZoom = true;
        //是否自动旋转
        controls.autoRotate = false;
        controls.autoRotateSpeed = 0.5;
        //设置相机距离原点的最远距离
        controls.minDistance = 1;
        //设置相机距离原点的最远距离
        controls.maxDistance = 2000;
        //是否开启右键拖拽
        controls.enablePan = true;
    }

    function render() {
        material.map.needsUpdate = true;
    }

    //窗口变动触发的函数
    function onWindowResize() {

        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);

    }

    function animate() {
        //更新控制器
        render();

        //更新性能插件
        stats.update();

        controls.update();

        renderer.render(scene, camera);

        requestAnimationFrame(animate);
    }

    function draw() {
        //兼容性判断
        if (!Detector.webgl) Detector.addGetWebGLMessage();
        initCanvas();
        initGui();
        initRender();
        initScene();
        initCamera();
        initLight();
        initModel();
        initControls();
        initStats();

        animate();
        window.onresize = onWindowResize;
    }


</script>
</html>
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值