FlakesTexture.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. * @three_import import { FlakesTexture } from 'three/addons/textures/FlakesTexture.js';
  6. */
  7. class FlakesTexture {
  8. /**
  9. * Generates a new flakes texture image. The result is a canvas
  10. * that can be used as an input for {@link CanvasTexture}.
  11. *
  12. * @param {number} [width=512] - The width of the image.
  13. * @param {number} [height=512] - The height of the image.
  14. * @return {HTMLCanvasElement} The generated image.
  15. */
  16. constructor( width = 512, height = 512 ) {
  17. const canvas = document.createElement( 'canvas' );
  18. canvas.width = width;
  19. canvas.height = height;
  20. const context = canvas.getContext( '2d' );
  21. context.fillStyle = 'rgb(127,127,255)';
  22. context.fillRect( 0, 0, width, height );
  23. for ( let i = 0; i < 4000; i ++ ) {
  24. const x = Math.random() * width;
  25. const y = Math.random() * height;
  26. const r = Math.random() * 3 + 3;
  27. let nx = Math.random() * 2 - 1;
  28. let ny = Math.random() * 2 - 1;
  29. let nz = 1.5;
  30. const l = Math.sqrt( nx * nx + ny * ny + nz * nz );
  31. nx /= l; ny /= l; nz /= l;
  32. context.fillStyle = 'rgb(' + ( nx * 127 + 127 ) + ',' + ( ny * 127 + 127 ) + ',' + ( nz * 255 ) + ')';
  33. context.beginPath();
  34. context.arc( x, y, r, 0, Math.PI * 2 );
  35. context.fill();
  36. }
  37. return canvas;
  38. }
  39. }
  40. export { FlakesTexture };