+ 2
What's wrong with this canvas code? Help Me PlEaSe
I wrote a simple code for dragging squares around the canvas: https://code.sololearn.com/WdtdAHJCBEav/?ref=app It works, I can drag squares, but there are very frequent misstouches. I mean, when i check the coordinates of user touch in "touchstart" for matching square coordinates, the condition returns false, even if the touch matches square . Please help
1 Réponse
0
Your issue is likely due to coordinate mismatches. Try these fixes:
1. Adjust for Canvas Offset
let rect = canvas.getBoundingClientRect();
let touchX = event.touches[0].clientX - rect.left;
let touchY = event.touches[0].clientY - rect.top;
2. Scale for Device Pixel Ratio
let scaleX = canvas.width / canvas.clientWidth;
let scaleY = canvas.height / canvas.clientHeight;
touchX *= scaleX;
touchY *= scaleY;
3. Improve Hit Detection
function isInside(x, y, square) {
return x >= square.x && x <= square.x + square.width &&
y >= square.y && y <= square.y + square.height;
}
4. Fix Multi-Touch & Scrolling Issues
canvas.addEventListener("touchstart", (e) => e.preventDefault(), { passive: false });
Try these and let me know if it helps