Guest User

Untitled

a guest
Nov 20th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Random Plot</title>
  5. <style>
  6. canvas { border: solid 1px; }
  7. th { font-family: monospace; }
  8. </style>
  9. </head>
  10. <body>
  11. <table>
  12. <tr>
  13. <td><canvas id="canvas1" width="400" height="300"></canvas></td>
  14. <td><canvas id="canvas2" width="400" height="300"></canvas></td>
  15. </tr>
  16. </table>
  17.  
  18. <script>
  19. 'use strict';
  20.  
  21. const drawRandomDots = (canvasId, num, acceptable = (x, y) => true) => {
  22. const canvas = document.getElementById(canvasId);
  23. const ctx = canvas.getContext("2d");
  24. ctx.fillStyle = "green";
  25.  
  26. while (num--) {
  27. while (true) {
  28. const x = Math.floor(Math.random() * canvas.width);
  29. const y = Math.floor(Math.random() * canvas.height);
  30. if (acceptable(x, y)) {
  31. ctx.beginPath();
  32. ctx.arc(x, y, 3, 0, Math.PI*2, false);
  33. ctx.fill();
  34. break;
  35. }
  36. }
  37. }
  38. };
  39.  
  40. const apartAtLeast = (distance) => {
  41. const memo = [];
  42. return (x, y) => {
  43. if (memo.every((e) => Math.hypot(x - e[0], y - e[1]) > distance)) {
  44. memo.push([x, y]);
  45. return true;
  46. } else {
  47. return false;
  48. }
  49. };
  50. };
  51.  
  52. drawRandomDots("canvas1", 500);
  53. drawRandomDots("canvas2", 500, apartAtLeast(10));
  54. </script>
  55. </body>
  56. </html>
Add Comment
Please, Sign In to add comment