一个交互式的WebGL代码,点击生成球体
init();
play();
function init() {
canvas = document.getElementById( 'canvas' );
document.onmousedown = onDocumentMouseDown;
document.onmouseup = onDocumentMouseUp;
document.onmousemove = onDocumentMouseMove;
document.ondblclick = onDocumentDoubleClick;
document.addEventListener( 'touchstart', onDocumentTouchStart, false );
document.addEventListener( 'touchmove', onDocumentTouchMove, false );
document.addEventListener( 'touchend', onDocumentTouchEnd, false );
window.addEventListener( 'deviceorientation', onWindowDeviceOrientation, false );
// init box2d
worldAABB = new b2AABB();
worldAABB.minVertex.Set( -200, -200 );
worldAABB.maxVertex.Set( window.innerWidth 200, window.innerHeight 200 );
world = new b2World( worldAABB, new b2Vec2( 0, 0 ), true );
setWalls();
reset();
}
function play() {
setInterval( loop, 1000 / 40 );
}
function reset() {
var i;
if ( bodies ) {
for ( i = 0; i < bodies.length; i ) {
var body = bodies[ i ]
canvas.removeChild( body.GetUserData().element );
world.DestroyBody( body );
body = null;
}
}
// color theme
theme = themes[ Math.random() * themes.length >> 0 ];
document.body.style[ 'backgroundColor' ] = theme[ 0 ];
bodies = [];
elements = [];
createInstructions();
for( i = 0; i < 10; i ) {
createBall();
}
}
//
function onDocumentMouseDown() {
isMouseDown = true;
return false;
}
function onDocumentMouseUp() {
isMouseDown = false;
return false;
}
function onDocumentMouseMove( event ) {
mouse.x = event.clientX;
mouse.y = event.clientY;
}
function onDocumentDoubleClick() {
reset();
}
function onDocumentTouchStart( event ) {
if( event.touches.length == 1 ) {
event.preventDefault();
// Faking double click for touch devices
var now = new Date().getTime();
if ( now - timeOfLastTouch < 250 ) {
reset();
return;
}
timeOfLastTouch = now;
mouse.x = event.touches[ 0 ].pageX;
mouse.y = event.touches[ 0 ].pageY;
isMouseDown = true;
}
}
function onDocumentTouchMove( event ) {
if ( event.touches.length == 1 ) {
event.preventDefault();
mouse.x = event.touches[ 0 ].pageX;
mouse.y = event.touches[ 0 ].pageY;
}
}
function onDocumentTouchEnd( event ) {
if ( event.touches.length == 0 ) {
event.preventDefault();
isMouseDown = false;
}
}
评论