Canvas signature on scroll changes mouse draw location

canvas, html, javascript, jquery

Solution

`event.clientX/Y` is relative to the top left corner of the viewport. So scroll isn't taken into account. `event.pageX/Y` is relative to the document. So it is the position on screen that the event happened including scroll. You can change all references to `clientX` to `pageX` and `clientY` to `pageY` and it should work.

Explanation of each screen/page/client XY.

Problem

I am trying to use canvas so that with a mouse a person can write their signature. Everything works until I stretch or scroll the screen then it draws the line in a different place away from the mouse. The Code: ``` function onMouseUp(event) { 'use strict'; mousePressed = false; } function onMouseMove(event) { 'use strict'; if (mousePressed) { event.preventDefault(); mouseX = event.clientX - can.offsetLeft - mleft; mouseY = event.clientY - can.offsetTop - mtop; ctx.lineTo(mouseX, mouseY); ctx.stroke(); } } function onMouseDown(event) { 'use strict'; mousePressed = true; mouseX = event.clientX - can.offsetLeft - mleft; mouseY = event.clientY - can.offsetTop - mtop; ctx.beginPath(); ctx.moveTo(mouseX, mouseY); } can.addEventListener('mousemove', onMouseMove, false); can.addEventListener('mousedown', onMouseDown, false); can.addEventListener('mouseup', onMouseUp, false); ``` HTML looks like: `<canvas id="signature" width="567" height="150"></canvas>`

Original source

Related problems