Chris 2pha Brown. Drupal developer Brisbane Australia

Chris Brown

Drupal, Javascript, Three.js, 3D

website blog
image for Three.js easy round / circular particles

Three.js easy round / circular particles

Today I came across a question on stackoverflow asking how to make round particles in Three.js (Three.js - give particles round form). I have seen questions like this a few times and the answers always seem to be to load an image and use it as a texture. People seem to forget that you can use a canvas as a texture map and you can draw pretty much what ever you want on a canvas. I have demonstrated this before when someone asked "Is it possible to use 2 textures (one on top of the other) as a Material without using custom Shaders?". See the fiddle HERE.

Basically, all you have to do is create a function that draws your canvas and returns a THREE.Texture object, assigning this THREE.Texture object to the map property of the Material.

Here is a function that creates a circle on a canvas:

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

Here is how to use it:

var pointMaterial =  new THREE.PointsMaterial({
  size: 20,
  map: createCircleTexture('#00ff00', 256),
  transparent: true,
  depthWrite: false

depthWrite must be set to false as per THIS issue on stack.

Add a comment

<b>, <i> and <code> tags are allowed.