I can’t move the second circle
var Point = function (x, y) { this.x = x; this.y = y; return this; } var Circle = function (point, radius) { this.point = point; this.radius = radius; this.isInside = function (pt) { return Math.pow(pt.x - point.x, 2) + Math.pow(pt.y - point.y, 2) < Math.pow(radius, 2); }; return this; } var element; var circle = new Circle(new Point(15, 15), 10); var circle2 = new Circle(new Point(25, 25), 10); var deltaCenter = null var drawCollection = [circle, circle2]; function Draw(){ var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); drawCollection.forEach(function(item){ drawCircle(item); }); } window.onload = function() { Draw(); element = document.getElementById('canvas'); element.addEventListener('mousedown', startDragging, false); element.addEventListener('mousemove', drag, false); element.addEventListener('mouseup', stopDragging, false); element.addEventListener('mouseout', stopDragging, false); } function startDragging(e) { var p = new Point(mouseX(e), mouseY(e)); if(circle.isInside(p)) { deltaCenter = new Point(px - circle.point.x, py - circle.point.y); } } function drag(e) { if(deltaCenter != null) { circle.point.x = (mouseX(e) - deltaCenter.x); circle.point.y = (mouseY(e) - deltaCenter.y); Draw(); } } cnt=0 function stopDragging(e) { deltaCenter = null; } function mouseX(e) { return e.clientX - element.offsetLeft; } function mouseY(e) { return e.clientY - element.offsetTop; } function drawCircle(circle) { var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.fillStyle = "red"; ctx.arc(circle.point.x, circle.point.y, circle.radius, 0, Math.PI*2, true); ctx.fill(); ctx.fillStyle = "green"; ctx.arc(circle2.point.x, circle2.point.y, circle2.radius, 0, Math.PI*2, true); ctx.fill(); }
<canvas id="canvas" width="400" height="300"></canvas>
(mouseX(e) - deltaCenter.x)
and this(mouseY(e) - deltaCenter.y)
. - Alex Krass