Skip to content

Instantly share code, notes, and snippets.

@razdvapoka
Created September 17, 2020 09:00
Show Gist options
  • Save razdvapoka/492d8c5d57a9af3fcd6974a33e0f1adb to your computer and use it in GitHub Desktop.
Save razdvapoka/492d8c5d57a9af3fcd6974a33e0f1adb to your computer and use it in GitHub Desktop.
update-sinewave-pointer
updatePointer = (pointer, { x, index, shift }) => {
const { pointerWidth, pointerHeight } = this.props
const { origin, freq, amplitude } = this.state
const baseY = Math.sin(freq * x + shift) * amplitude + origin.y
pointer.setAttribute('points', `
${x}, ${baseY}
${x + pointerWidth}, ${Math.sin(freq * x + shift) * amplitude + origin.y - pointerHeight / 2}
${x}, ${Math.sin(freq * x + shift) * amplitude + origin.y - pointerHeight}
`)
// The angle of the pointer's rotation must be the same as the curve's slope.
//
// First, we calculate the derivative of the curve's function at the pointer's X-coord.
// Since the derivative is the tangent of the curve's slope,
// we just take the arctangent of it and convert to degrees.
// The point of rotation is the base of the pointer.
const derivative = freq * Math.cos(freq * x + shift) * amplitude
pointer.setAttribute('transform', `
rotate(
${radToDeg(Math.atan(derivative))},
${x},
${baseY}
)
translate(-${pointerWidth / 2}, ${pointerHeight / 2})
`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment