Skip to content

Instantly share code, notes, and snippets.

@sabha
Created April 28, 2019 17:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sabha/ad80b4763999108000eb2ac4c9b306fa to your computer and use it in GitHub Desktop.
Save sabha/ad80b4763999108000eb2ac4c9b306fa to your computer and use it in GitHub Desktop.
Circle Interaction Pattern
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="800" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
function Line(x1,y1,x2,y2,alpha=1){
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.strokeStyle = `rgba(0,0,0,${alpha})`;
ctx.stroke();
ctx.closePath();
}
function circle(x,y, r=70){
ctx.beginPath();
ctx.arc(x, y, r, 0, 2 * Math.PI);
ctx.stroke();
}
var r = 100;
var counter = 0;
var angle = 0;
var offX1 = 100;
var offY1 = 150;
var offX2 = 400;
var offY2 = 400;
var intersections = [];
function line_intersect(x1, y1, x2, y2, x3, y3, x4, y4)
{
var ua, ub, denom = (y4 - y3)*(x2 - x1) - (x4 - x3)*(y2 - y1);
if (denom == 0) {
return null;
}
ua = ((x4 - x3)*(y1 - y3) - (y4 - y3)*(x1 - x3))/denom;
ub = ((x2 - x1)*(y1 - y3) - (y2 - y1)*(x1 - x3))/denom;
return {
x: x1 + ua * (x2 - x1),
y: y1 + ub * (y2 - y1),
seg1: ua >= 0 && ua <= 1,
seg2: ub >= 0 && ub <= 1
};
}
function normalize(min, max) {
var delta = max - min;
return function (val) {
return (val - min) / delta;
};
}
var draw = setInterval(function(){
counter++;
//ctx.fillRect(0, 0, 500, 500);
ctx.clearRect(0,0,800,500);
angle+=.8;
x1 = offX1+(r*Math.cos(angle*Math.PI/180));
y1 = offY1+(r*Math.sin(angle*Math.PI/180));
Line(offX1,offY1,x1,y1);
x2 = x1+700;
y2 = y1;
Line(x1,y1,x2,y2);
circle(offX1,offY1, r);
angle1 = angle;
angle1 = angle*.49;
x3 = offX2+(r*Math.cos(angle1*Math.PI/180));
y3 = offY2+(r*Math.sin(angle1*Math.PI/180));
Line(offX2,offY2,x3,y3);
circle(offX2,offY2, r);
x4 = x3;
y4 = y3-700;
Line(x3,y3,x4,y4);
//console.log(counter%3)
if(counter%5 === 0){
var intersection = line_intersect(x1, y1, x2, y2, x3, y3, x4, y4);
intersections.push({x: intersection.x, y:intersection.y});
}
intersections.forEach((p, i) => {
if(i>0 && i < intersections.length-1) {
//console.log(i/intersections.length)
Line(p.x,p.y,intersections[i+1].x,intersections[i+1].y, 1.2-(i/intersections.length));
}
});
if(intersections.length > 2) {
var length = intersections.length;
var a = intersections[0].x - intersections[length-1].x;
var b = intersections[0].y - intersections[length-1].y;
var c = Math.sqrt( a*a + b*b );
//console.log(c);
if(c < 1) {
console.log('STOP');
//clearInterval(draw);
}
}
}, 1);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment