canvas-random-dots.html 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <!-- Licensed under a BSD license. See license.html for license -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
  7. <title>Canvas Random Dots</title>
  8. </head>
  9. <body>
  10. </body>
  11. <script type="module">
  12. function main() {
  13. const ctx = document.createElement( 'canvas' ).getContext( '2d' );
  14. document.body.appendChild( ctx.canvas );
  15. ctx.canvas.width = 256;
  16. ctx.canvas.height = 256;
  17. ctx.fillStyle = '#FFF';
  18. ctx.fillRect( 0, 0, ctx.canvas.width, ctx.canvas.height );
  19. function randInt( min, max ) {
  20. if ( max === undefined ) {
  21. max = min;
  22. min = 0;
  23. }
  24. return Math.random() * ( max - min ) + min | 0;
  25. }
  26. function drawRandomDot() {
  27. ctx.fillStyle = `#${randInt( 0x1000000 ).toString( 16 ).padStart( 6, '0' )}`;
  28. ctx.beginPath();
  29. const x = randInt( 256 );
  30. const y = randInt( 256 );
  31. const radius = randInt( 10, 64 );
  32. ctx.arc( x, y, radius, 0, Math.PI * 2 );
  33. ctx.fill();
  34. }
  35. function render() {
  36. drawRandomDot();
  37. requestAnimationFrame( render );
  38. }
  39. requestAnimationFrame( render );
  40. }
  41. main();
  42. </script>
  43. </html>