Workshop › Angry Birds-style Slingshot › Step 20 of 47
Next we aim with the mouse or a finger, like a real sling. Two helpers first: toCanvas turns a pointer event into a
point in canvas pixels, and pull turns a point behind the sling into an angle and a pull.
```js
function toCanvas(event) {
const rect = canvas.getBoundingClientRect()
return {
x: ((event.clientX - rect.left) * canvas.width) / rect.width,
y: ((event.clientY - rect.top) * canvas.height) / rect.height,
}
}
// Drag back from the sling like a real one: the bird flies the other way, harder the further you pull.
function pull(point) {
const dx = SLING.x - point.x
const dy = SLING.y - point.y
aim.angle = Math.atan2(dy, dx)
aim.pull = Math.min(MAX_PULL, Math.hypot(dx, dy))
}
```getBoundingClientRect() gives where the canvas is on the page and how big it is shown. Subtracting rect.left
and scaling by canvas.width / rect.width turns page pixels into canvas pixels.dx, dy is the arrow from the point to the sling. Math.atan2(dy, dx) is the direction of that arrow as an angle,
Math.hypot(dx, dy) its length (the straight distance).Write both functions above function draw() {.
Skills: Keyboard and mouse input, Velocity and gravity
← See the path before you shoot Grab the sling →