From 53112c5ea0874f36af3c250688c60fb273328bf9 Mon Sep 17 00:00:00 2001 From: Peter Hart Date: Mon, 27 Apr 2020 21:16:20 -0400 Subject: [PATCH] fix mouse pointer location --- README.md | 3 +++ drawing-program/index.html | 20 +++++++++++++++----- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 7e5cea9..5c5667c 100644 --- a/README.md +++ b/README.md @@ -3,3 +3,6 @@ Simple repo for keeping track of attempts to work with various web technologies. + + +## TODOS diff --git a/drawing-program/index.html b/drawing-program/index.html index 0a2f091..d70fd5f 100644 --- a/drawing-program/index.html +++ b/drawing-program/index.html @@ -85,10 +85,19 @@ const drawingElem = document.getElementById('drawing') const colorElem = document.getElementById('color') + + + function mousePosition(e) { + const canvasBounds = canvas.getBoundingClientRect() + const canvasSize = [canvas.width, canvas.height] + const x = e.pageX - canvasBounds.left - scrollX + const y = e.pageY - canvasBounds.top - scrollY + return [x/canvasBounds.width*canvasSize[0], y/canvasBounds.height*canvasSize[1]] + } canvas.addEventListener('mousedown', e => { drawing = true; - lastPosition = [e.clientX, e.clientY] + lastPosition = mousePosition(e) updateDebug() }) canvas.addEventListener('mouseup', e => { @@ -104,20 +113,21 @@ if (!drawing) { lastPosition = undefined } else { - lastPosition = [e.clientX, e.clientY] + lastPosition = mousePosition(e) } }) canvas.addEventListener('mousemove', e => { if (drawing) { + const newPosition = mousePosition(e) if (lastPosition !== undefined) { - console.log(`lineTo: (${e.clientX}, ${e.clientY})`) + console.log(`lineTo: (${newPosition[0]}, ${newPosition[1]})`) context.beginPath() context.moveTo(lastPosition[0], lastPosition[1]) - context.lineTo(e.clientX, e.clientY) + context.lineTo(newPosition[0], newPosition[1]) context.stroke() } - lastPosition = [e.clientX, e.clientY] + lastPosition = newPosition } })