html5的canvas实现3d雪花飘舞效果
程序员文章站
2023-12-09 14:30:39
使用HTML5 的canvas标签和 three.js 实现了 3D 的雪花飞舞效果。你可以拖动鼠标进行旋转,需要在支持CSS3属性的浏览器下浏览... 13-12-27...
复制代码
代码如下:var screen_width = window.innerwidth;
var screen_height = window.innerheight;</p> <p> var container;</p> <p> var particle;</p> <p> var camera;
var scene;
var renderer;</p> <p> var mousex = 0;
var mousey = 0;</p> <p> var windowhalfx = window.innerwidth / 2;
var windowhalfy = window.innerheight / 2;
var particles = [];
var particleimage = new image();//three.imageutils.loadtexture( "img/particlesmoke.png" );
particleimage.src = 'images/particlesmoke.png'; </p> <p>
function init() {</p> <p> container = document.createelement('div');
document.body.appendchild(container);</p> <p> camera = new three.perspectivecamera( 75, screen_width / screen_height, 1, 10000 );
camera.position.z = 1000;</p> <p> scene = new three.scene();
scene.add(camera);
renderer = new three.canvasrenderer();
renderer.setsize(screen_width, screen_height);
var material = new three.particlebasicmaterial( { map: new three.texture(particleimage) } );
for (var i = 0; i < 500; i++) {</p> <p> particle = new particle3d( material);
particle.position.x = math.random() * 2000 - 1000;
particle.position.y = math.random() * 2000 - 1000;
particle.position.z = math.random() * 2000 - 1000;
particle.scale.x = particle.scale.y = 1;
scene.add( particle );
particles.push(particle);
}</p> <p> container.appendchild( renderer.domelement );</p> <p>
document.addeventlistener( 'mousemove', ondocumentmousemove, false );
document.addeventlistener( 'touchstart', ondocumenttouchstart, false );
document.addeventlistener( 'touchmove', ondocumenttouchmove, false );
setinterval( loop, 1000 / 60 );
}
function ondocumentmousemove( event ) {</p> <p> mousex = event.clientx - windowhalfx;
mousey = event.clienty - windowhalfy;
}</p> <p> function ondocumenttouchstart( event ) {</p> <p> if ( event.touches.length == 1 ) {</p> <p> event.preventdefault();</p> <p> mousex = event.touches[ 0 ].pagex - windowhalfx;
mousey = event.touches[ 0 ].pagey - windowhalfy;
}
}</p> <p> function ondocumenttouchmove( event ) {</p> <p> if ( event.touches.length == 1 ) {</p> <p> event.preventdefault();</p> <p> mousex = event.touches[ 0 ].pagex - windowhalfx;
mousey = event.touches[ 0 ].pagey - windowhalfy;
}
}</p> <p> //</p> <p> function loop() {</p> <p> for(var i = 0; i<particles.length; i++)
{</p> <p> var particle = particles[i];
particle.updatephysics();
with(particle.position)
{
if(y<-1000) y+=2000;
if(x>1000) x-=2000;
else if(x<-1000) x+=2000;
if(z>1000) z-=2000;
else if(z<-1000) z+=2000;
}
}
camera.position.x += ( mousex - camera.position.x ) * 0.05;
camera.position.y += ( - mousey - camera.position.y ) * 0.05;
camera.lookat(scene.position); </p> <p> renderer.render( scene, camera );</p> <p>
}