D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
wonga00
Full window
Github gist
dithered paths
<script src="https://d3js.org/d3.v4.min.js"></script> <body> <canvas width=800 height=600></canvas> <script> let canvas = document.querySelector('canvas'), ctx = canvas.getContext('2d'), height = 600, width = 800, pChangeDirection = 0.9; // points of a triangle let p1 = { x: 226, y: 425 }; let p2 = { x: 428, y: 130 }; let p3 = { x: 623, y: 425 } function drawPath(ctx, points) { ctx.beginPath(); ctx.strokeStyle = 'rgba(0, 0, 0, 1)'; ctx.lineWidth = 1; ctx.moveTo(points[0].x, points[0].y); for (let i = 1; i < points.length; i++) { ctx.lineTo(points[i].x, points[i].y); } ctx.stroke(); } function getDist(p1, p2) { return (p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y); } function computePath(start, end) { let count = 0, path = [], point = { x: start.x, y: start.y }, distThresh = 10, dist = 1000, angle = 0, angleResolution = Math.PI / 4, angleSpread = Math.PI / 4, speedScale = d3.scaleLinear() .domain([100, 0]).range([3, 0.01]).clamp(true); while (dist > distThresh && count < 10000) { if (Math.random() < pChangeDirection) { let desiredAngle = Math.atan2(end.y - point.y, end.x - point.x); angle = d3.randomNormal(desiredAngle, angleSpread)(); angle = Math.round(angle / angleResolution) * angleResolution; } let speed = speedScale(dist); point.x += Math.cos(angle) * speed; // move in the direction point.y += Math.sin(angle) * speed; count += 1; dist = getDist(point, end); path.push({ x: point.x, y: point.y }); } return path; } ctx.globalAlpha = 0.2; function draw() { ctx.fillStyle = 'rgba(255, 255, 255, 0.6)'; ctx.fillRect(0, 0, width, height); drawPath(ctx, computePath(p1, p2)); drawPath(ctx, computePath(p2, p3)); drawPath(ctx, computePath(p3, p1)); window.requestAnimationFrame(draw); } window.requestAnimationFrame(draw); </script> </body>
https://d3js.org/d3.v4.min.js