學習Three.js——粒子、點雲(Sprite,PointCloud)
阿新 • • 發佈:2018-12-23
粒子
使用THREE.SpriteMaterial()
和THREE.Sprite()
即可建立單個粒子
建立過程
function createSprites() {
var material = new THREE.SpriteMaterial();
for (var x = -5; x < 5; x++) {
for (var y = -5; y < 5; y++) {
var sprite = new THREE.Sprite(material) ;
sprite.position.set(x * 10, y * 10, 0);
scene.add(sprite);
}
}
}
建立SpriteMaterial後,將SpriteMaterial放入Sprite即可建立單個粒子
點雲
建立點雲很簡單,先建立普通的Geometry物件,再使用PointCloudMaterial點雲材質即可
function createParticles() {
var geom = new THREE.Geometry();
var material = new THREE.PointCloudMaterial({size: 4, vertexColors: true, color: 0xffffff});
for (var x = -5; x < 5; x++) {
for (var y = -5; y < 5; y++) {
var particle = new THREE.Vector3(x * 10, y * 10, 0);
geom.vertices.push(particle);
geom.colors.push(new THREE.Color(Math.random() * 0x00ffff));
}
}
var cloud = new THREE.PointCloud(geom, material);
scene.add(cloud);
}
SpriteMaterial
和PointCloudMaterial
的一些屬性如下:
color
:指定所有粒子的顏色
map
:粒子使用的紋理
size
:粒子的大小
sizeAnnutation
:指定為true,那麼粒子的大小取決於離攝像機距離的遠近
vertexColors
:指定為THREE.VertexColors時使用自己定製的顏色而不是color屬性指定的顏色,預設為THREE.NoColors
opacity
:透明度,和transparent配合使用
transparent
:是否使用透明
blending
:融合模式
fog
:是否受到霧化的影響
粒子和點雲的區別:粒子定製化程度高,可以管理到每一個粒子,但資源消耗大;點雲統一管理所有粒子,資源消耗小,但是不便於對每一個粒子單獨進行處理。
使用紋理
通過HTML5畫布畫紋理
var getTexture = function () {
var canvas = document.createElement('canvas');
canvas.width = 32;
canvas.height = 32;
var ctx = canvas.getContext('2d');
// the body
ctx.translate(-81, -84);
ctx.fillStyle = "orange";
ctx.beginPath();
ctx.moveTo(83, 116);
ctx.lineTo(83, 102);
ctx.bezierCurveTo(83, 94, 89, 88, 97, 88);
ctx.bezierCurveTo(105, 88, 111, 94, 111, 102);
ctx.lineTo(111, 116);
ctx.lineTo(106.333, 111.333);
ctx.lineTo(101.666, 116);
ctx.lineTo(97, 111.333);
ctx.lineTo(92.333, 116);
ctx.lineTo(87.666, 111.333);
ctx.lineTo(83, 116);
ctx.fill();
// the eyes
ctx.fillStyle = "white";
ctx.beginPath();
ctx.moveTo(91, 96);
ctx.bezierCurveTo(88, 96, 87, 99, 87, 101);
ctx.bezierCurveTo(87, 103, 88, 106, 91, 106);
ctx.bezierCurveTo(94, 106, 95, 103, 95, 101);
ctx.bezierCurveTo(95, 99, 94, 96, 91, 96);
ctx.moveTo(103, 96);
ctx.bezierCurveTo(100, 96, 99, 99, 99, 101);
ctx.bezierCurveTo(99, 103, 100, 106, 103, 106);
ctx.bezierCurveTo(106, 106, 107, 103, 107, 101);
ctx.bezierCurveTo(107, 99, 106, 96, 103, 96);
ctx.fill();
// the pupils
ctx.fillStyle = "blue";
ctx.beginPath();
ctx.arc(101, 102, 2, 0, Math.PI * 2, true);
ctx.fill();
ctx.beginPath();
ctx.arc(89, 102, 2, 0, Math.PI * 2, true);
ctx.fill();
var texture = new THREE.Texture(canvas);
texture.needsUpdate = true;
return texture;
};
通過載入圖片作為紋理
var texture = THREE.ImageUtils.loadTexture("texture.png");
紋理圖片一般為長寬相等且為2的冪,背景為黑色的影象,如:
從高階幾何體建立THREE.PointCloud
很簡單,只需要把PointCloud建構函式中的幾何體傳入一個高階幾何體即可
var geom = new THREE.KnotGeometry(...)
var cloud = new THREE.PointCloud(geom,material)