Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Created October 5, 2013 04:31
Show Gist options
  • Save joyrexus/6836700 to your computer and use it in GitHub Desktop.
Save joyrexus/6836700 to your computer and use it in GitHub Desktop.
Infer angle based on mouse position

Animation trigged by mousemove event where we infer angular measure (relative to a center point) based on mouse position.

Another follow-up experiment inspired by Math for Pictures.

<!DOCTYPE html>
<meta charset="utf-8">
<script src="http://jashkenas.github.io/coffee-script/extras/coffee-script.js"></script>
<script src="https://s3-eu-west-1.amazonaws.com/svgjs/svg.js"></script>
<style>
line, polyline, circle, ellipse {
stroke: steelblue;
stroke-width: 10;
}
polyline {
fill: none;
}
circle, ellipse {
fill: aliceblue;
}
rect {
fill: none;
stroke: #999;
stroke-width: 2;
}
</style>
<body>
<div id="canvas"></div>
<script type="text/coffeescript">
w = 960
h = 500
c = # center
x: w/2
y: h/2
draw = SVG('canvas').size(w, h)
draw.rect(w, h)
C = draw.circle(300).center(c.x, c.y)
L = draw.line(c.x, c.y, c.x+150, c.y).rotate(0, c.x, c.y)
R2D = 180 / Math.PI # convert radians to degrees
document.onmousemove = (e) ->
x = e.offsetX - c.x
y = e.offsetY - c.y
θ = R2D * Math.atan2(y, x)
θ = θ - 360 if θ > 0
L.rotate(θ, c.x, c.y)
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment