Three.js-给粒子圆形

Lav*_*nen 4 javascript three.js

我目前正在尝试three.js。我想在下面的示例中更改代码,以便点是圆形的,而不是正方形。

Codepen示例

我发现了另一个示例,称为canvas粒子random,它具有圆形粒子,基本上,脚本中的唯一区别如下:

var PI2 = Math.PI * 2;
var program = function ( context ) {

    context.beginPath();
    context.arc( 0, 0, 0.5, 0, PI2, true );
    context.fill();

};
Run Code Online (Sandbox Code Playgroud)

我以为如果将其添加到其他脚本中,则粒子将变得圆润。但是,当我将上述脚本添加到第一个脚本时,它不起作用(我只得到了蓝屏)。

有人知道我在做什么错吗?

小智 6

尽管这个问题在 2 年前就有人问过了,但我认为补充一点你总是可以使用three.js ShaderMaterial编写自己的片段着色器会很有用

let geom = new three.Geometry();
geom.vertices.push(new three.Vector3(0,0,0));
let material = new three.ShaderMaterial({
    transparent: true,
    uniforms: {
        size: {value: 10},
        scale: {value: 1},
        color: {value: new three.Color('maroon')}
    },
    vertexShader: three.ShaderLib.points.vertexShader,
    fragmentShader: `
    uniform vec3 color;
    void main() {
        vec2 xy = gl_PointCoord.xy - vec2(0.5);
        float ll = length(xy);
        gl_FragColor = vec4(color, step(ll, 0.5));
    }
    `
});
let points = new three.Points(geom, material);
Run Code Online (Sandbox Code Playgroud)


2ph*_*pha 5

正如其他人所说,您可以在PointsMaterial中将纹理用作地图。
但是,如果您只想绘制圆圈,则一种更简单的方法可能是使用画布动态创建地图(这是您发布的代码似乎正在尝试做的事情)。

在这里很麻烦,您的代码已更新为使用画布作为纹理贴图。
注意:我已经更改了参数对象中的颜色,以使使用其他颜色变得更加明显。

在画布上创建圆以用作地图的功能。

function createCanvasMaterial(color, size) {
  var matCanvas = document.createElement('canvas');
  matCanvas.width = matCanvas.height = size;
  var matContext = matCanvas.getContext('2d');
  // create exture object from canvas.
  var texture = new THREE.Texture(matCanvas);
  // Draw a circle
  var center = size / 2;
  matContext.beginPath();
  matContext.arc(center, center, size/2, 0, 2 * Math.PI, false);
  matContext.closePath();
  matContext.fillStyle = color;
  matContext.fill();
  // need to set needsUpdate
  texture.needsUpdate = true;
  // return a texture made from the canvas
  return texture;
}
Run Code Online (Sandbox Code Playgroud)

使用参数对象在循环中创建地图画布。

  for (i = 0; i < parameters.length; i++) {

    color = parameters[i][0];
    size = parameters[i][1];

    var hexColor = new THREE.Color(color[0], color[1], color[2]).getHexString();

    materials[i] = new THREE.PointsMaterial({
        size: 20,
        map: createCanvasMaterial('#'+hexColor, 256),
        transparent: true,
        depthWrite: false
    });

    particles = new THREE.Points(geometry, materials[i]);

    particles.rotation.x = Math.random() * 6;
    particles.rotation.y = Math.random() * 6;
    particles.rotation.z = Math.random() * 6;

    scene.add(particles);

  }
Run Code Online (Sandbox Code Playgroud)

必须在材质上将depthWrite设置为false。请参阅问题。

我现在已经在Three.js画布粒子上创建了博客文章