FlakesTexture.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * Utility class for generating a flakes texture image. This image might be used
  3. * as a normal map to produce a car paint like effect.
  4. */
  5. class FlakesTexture {
  6. /**
  7. * Generates a new flakes texture image. The result is a canvas
  8. * that can be used as an input for {@link CanvasTexture}.
  9. *
  10. * @param {number} [width=512] - The width of the image.
  11. * @param {number} [height=512] - The height of the image.
  12. * @return {HTMLCanvasElement} The generated image.
  13. */
  14. constructor( width = 512, height = 512 ) {
  15. const canvas = document.createElement( 'canvas' );
  16. canvas.width = width;
  17. canvas.height = height;
  18. const context = canvas.getContext( '2d' );
  19. context.fillStyle = 'rgb(127,127,255)';
  20. context.fillRect( 0, 0, width, height );
  21. for ( let i = 0; i < 4000; i ++ ) {
  22. const x = Math.random() * width;
  23. const y = Math.random() * height;
  24. const r = Math.random() * 3 + 3;
  25. let nx = Math.random() * 2 - 1;
  26. let ny = Math.random() * 2 - 1;
  27. let nz = 1.5;
  28. const l = Math.sqrt( nx * nx + ny * ny + nz * nz );
  29. nx /= l; ny /= l; nz /= l;
  30. context.fillStyle = 'rgb(' + ( nx * 127 + 127 ) + ',' + ( ny * 127 + 127 ) + ',' + ( nz * 255 ) + ')';
  31. context.beginPath();
  32. context.arc( x, y, r, 0, Math.PI * 2 );
  33. context.fill();
  34. }
  35. return canvas;
  36. }
  37. }
  38. export { FlakesTexture };
粤ICP备19079148号