Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <title>Random Plot</title>
- <style>
- canvas { border: solid 1px; }
- th { font-family: monospace; }
- </style>
- </head>
- <body>
- <table>
- <tr>
- <td><canvas id="canvas1" width="400" height="300"></canvas></td>
- <td><canvas id="canvas2" width="400" height="300"></canvas></td>
- </tr>
- </table>
- <script>
- 'use strict';
- const drawRandomDots = (canvasId, num, acceptable = (x, y) => true) => {
- const canvas = document.getElementById(canvasId);
- const ctx = canvas.getContext("2d");
- ctx.fillStyle = "green";
- while (num--) {
- while (true) {
- const x = Math.floor(Math.random() * canvas.width);
- const y = Math.floor(Math.random() * canvas.height);
- if (acceptable(x, y)) {
- ctx.beginPath();
- ctx.arc(x, y, 3, 0, Math.PI*2, false);
- ctx.fill();
- break;
- }
- }
- }
- };
- const apartAtLeast = (distance) => {
- const memo = [];
- return (x, y) => {
- if (memo.every((e) => Math.hypot(x - e[0], y - e[1]) > distance)) {
- memo.push([x, y]);
- return true;
- } else {
- return false;
- }
- };
- };
- drawRandomDots("canvas1", 500);
- drawRandomDots("canvas2", 500, apartAtLeast(10));
- </script>
- </body>
- </html>
Add Comment
Please, Sign In to add comment