Bir*_*son 5 html javascript canvas webgl three.js
我的显示器的分辨率为 7680x4320 像素。我想显示多达 400 万个不同颜色的方块。我想用滑块更改正方形的数量。如果目前有两个版本。一个带有 canvas-fillRect 的看起来像这样:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
for (var i = 0; i < num_squares; i ++) {
ctx.fillStyle = someColor;
ctx.fillRect(pos_x, pos_y, pos_x + square_width, pos_y + square_height);
// set pos_x and pos_y for next square
}
Run Code Online (Sandbox Code Playgroud)
还有一个使用 webGL 和three.js。相同的循环,但我为每个正方形创建了一个盒子几何图形和一个网格:
var geometry = new THREE.BoxGeometry( width_height, width_height, 0);
for (var i = 0; i < num_squares; i ++) {
var material = new THREE.MeshLambertMaterial( { color: Math.random() * 0xffffff } );
material.emissive = new THREE.Color( Math.random(), Math.random(), Math.random() );
var object = new THREE.Mesh( geometry, material );
}
Run Code Online (Sandbox Code Playgroud)
它们都可以很好地处理几千个正方形。第一个版本最多可以做一百万个正方形,但是超过一百万的所有东西都非常慢。我想动态更新颜色和方块数。
有没有人有关于如何使用 Three.js/WebGL/Canvas 提高效率的提示?
// Remove all objects from scene
var obj, i;
for ( i = scene.children.length - 1; i >= 0 ; i -- ) {
obj = scene.children[ i ];
if ( obj !== camera) {
scene.remove(obj);
}
}
// Fill scene with new objects
num_squares = gui_dat.squareNum;
var window_pixel = window.innerWidth * window.innerHeight;
var pixel_per_square = window_pixel / num_squares;
var width_height = Math.floor(Math.sqrt(pixel_per_square));
var geometry = new THREE.BoxGeometry( width_height, width_height, 0);
var pos_x = width_height/2;
var pos_y = width_height/2;
for (var i = 0; i < num_squares; i ++) {
//var object = new THREE.Mesh( geometry, );
var material = new THREE.Material()( { color: Math.random() * 0xffffff } );
material.emissive = new THREE.Color( Math.random(), Math.random(), Math.random() );
var object = new THREE.Mesh( geometry, material );
object.position.x = pos_x;
object.position.y = pos_y;
pos_x += width_height;
if (pos_x > window.innerWidth) {
pos_x = width_height/2;
pos_y += width_height;
}
scene.add( object );
}
Run Code Online (Sandbox Code Playgroud)
我建议尝试 pixi 框架(如上面的评论中所述)。
它有 webgl 渲染器,并且一些基准测试非常有前途。
http://www.goodboydigital.com/pixijs/bunnymark_v3/
它可以处理动画精灵的分配。如果您的应用程序仅显示方块,并且没有动画,并且它们是非常简单的精灵(只有一种颜色),那么它将提供比上面的演示链接更好的性能。