There is nothing messy with JavaScript, you just need a lot more practice…
Few things on your code, as they point out in the comments you have a typo cleintY
, also you have to substract the canvas.offset to get the correct position of the mouse.
Those points should be an array that way you can add more and everything will work.
Here is your code working
var canvas = document.getElementById('cv2');
canvas.addEventListener('mousedown', onMouseDown);
var c = canvas.getContext('2d');
var points = [{x:18, y:12},{x:50, y:50},{x:180, y:90},{x:250, y:50}];
var dragPoint = null;
draw();
function draw() {
c.clearRect(0, 0, canvas.width, canvas.height);
points.forEach(p => drawPoint(p));
drawLines();
}
function drawPoint(p) {
c.beginPath();
c.lineWidth = 2;
c.arc(p.x, p.y, 10, 0, 2 * Math.PI, false);
c.stroke();
c.fill();
}
function drawLines() {
c.beginPath();
c.lineWidth = 2;
points.forEach(p => c.lineTo(p.x, p.y));
c.stroke();
}
function findDragPoint(x, y) {
for (i = 0; i < points.length; i++) {
if (hitTest(points[i], x, y)) return points[i];
};
return null;
}
function onMouseDown(event) {
dragPoint = findDragPoint(event.clientX- canvas.offsetLeft, event.clientY- canvas.offsetTop);
if (dragPoint) {
dragPoint.x = event.clientX- canvas.offsetLeft;
dragPoint.y = event.clientY- canvas.offsetTop;
draw();
canvas.addEventListener("mousemove", onMouseMove);
canvas.addEventListener("mouseup", onMouseUp);
}
}
function onMouseMove(event) {
dragPoint.x = event.clientX- canvas.offsetLeft;
dragPoint.y = event.clientY- canvas.offsetTop;
draw();
}
function onMouseUp() {
canvas.removeEventListener("mousemove", onMouseMove);
canvas.removeEventListener("mouseup", onMouseUp);
}
function hitTest(p, x, y) {
var dx = p.x - x, dy = p.y - y;
return Math.sqrt(dx * dx + dy * dy) <= 10;
}
<canvas id='cv2' width=400 height=120></canvas>
1
solved What’s wrong with the addEventListeners