i want to let my users to draw their signatures to approve that they accept my user agreements. I created canvas and javascript code, but instead of drawing under the mouse, it draws next to it.
You can see how it works here:
JS CODE:
// Select the canvas element
const canvas = document.getElementById('signature-pad');
const ctx = canvas.getContext('2d');
// Set up event listeners
let isDrawing = false;
let lastX = 0;
let lastY = 0;
canvas.addEventListener('mousedown', e => {
isDrawing = true;
lastX = e.offsetX;
lastY = e.offsetY;
});
canvas.addEventListener('mousemove', e => {
if (isDrawing) {
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
lastX = e.offsetX;
lastY = e.offsetY;
}
});
canvas.addEventListener('mouseup', () => {
isDrawing = false;
});
canvas.addEventListener('mouseout', () => {
isDrawing = false;
});
// Set up button event listeners
const clearButton = document.getElementById('clear-button');
clearButton.addEventListener('click', () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
const saveButton = document.getElementById('save-button');
saveButton.addEventListener('click', () => {
const dataURL = canvas.toDataURL();
console.log(dataURL);
});
HTML CODE:
<canvas id="signature-pad" width="400" height="200"></canvas>
I was trying to do something with offsets but still no idea.
2
Answers
You can get the mouse position using this code
Check out the replit here: https://VeneratedJovialCryptos.hackinggo306.repl.co
I have create an html file with the JS that is related just to the canvas, and everything works as expected. Here is the code:
Here is the result of running this html file: https://streamable.com/69bwa9
So you can try to place this code in a separate file, and see if everything works- if yes, then you should look for a problem in other parts of the code, if still no, maybe if is something about differences between physical machines, I am trying this on Mac.