I’m doing a project, learning canvas.
My basic operations work (dragging mouse over the canvas to draw, clearing)
but when I switch to touch, it draws offset, like diagonally down and right from where im clicking
here’s my codepen: https://codepen.io/Dolevy97/pen/ExzwaLe
and the relevant lines of code:
function onMove(ev) {
if (!gIsDrawing) return
gCtx.fillStyle = gBackgroundColor
gCtx.strokeStyle = gShape.color
gCtx.lineWidth = gShape.size
const pos = getEvPos(ev)
//* Calc the delta, the diff we moved
const dx = pos.x - gPrevPos.x
const dy = pos.y - gPrevPos.y
move(dx, dy)
gCtx.fillStyle = gBackgroundColor
if (gShape.shape === 'pen') {
gCtx.lineTo(pos.x, pos.y)
gCtx.stroke()
} else if (gShape.shape === 'square') {
gCtx.strokeRect(pos.x, pos.y, 50, 50)
gCtx.fillRect(pos.x, pos.y, 50, 50)
} else if (gShape.shape === 'triangle') {
gCtx.moveTo(pos.x, pos.y)
gCtx.lineTo(pos.x + 80, pos.y + 80)
gCtx.lineTo(pos.x - 20, pos.y + 100)
gCtx.closePath()
gCtx.fill()
gCtx.stroke()
} else if (gShape.shape === 'circle') {
gCtx.beginPath()
gCtx.arc(pos.x, pos.y, gShape.size * 10, 0, Math.PI * 2)
gCtx.fill()
gCtx.stroke()
}
//* Save the last pos, we remember where we`ve been and move accordingly
gPrevPos = pos
}
function getEvPos(ev) {
let pos = {
x: ev.offsetX,
y: ev.offsetY,
}
if (TOUCH_EVS.includes(ev.type)) {
ev.preventDefault()
ev = ev.changedTouches[0]
pos = {
x: ev.pageX - ev.target.offsetLeft - ev.target.clientLeft,
y: ev.pageY - ev.target.offsetTop - ev.target.clientTop
}
}
return pos
}
I can’t understand what’s not working because it seems that it works for others with the same getEvPos.
Thank you!
I tried playing around with it, but to my understanding, the calculations in getEvPos are constant and shouldn’t be touched. So it’s probably something in my ‘onMove’