2017-08-10 38 views
-1

我有一個應用程序,我需要將創建的點移動到畫布的某個部分。我該怎麼做?動態拖動點在畫布中的內容

$("#canvas").click(function(e){ 
     getPosition(e); 
    }); 

    var pointSize = 1; 

    function getPosition(event){ 
     var rect = canvas.getBoundingClientRect(); 
     var x = event.clientX - rect.left; 
     var y = event.clientY - rect.top; 
      console.log(x,y) 
     drawCoordinates(x,y); 
    } 

    function drawCoordinates(x,y){ 
     var ctx = document.getElementById("canvas").getContext("2d"); 


     ctx.fillStyle = "#ff2626"; // Red color 

     ctx.beginPath(); 
     ctx.arc(x, y, pointSize, 0, Math.PI * 2, true); 
     ctx.fill(); 
    } 

http://jsfiddle.net/bfe8160h/

enter image description here

+0

所以,如果你點擊一個空的空間,應該創建一個新的點,如果你點擊某個現有的時候,你應該能夠拖動它? –

+0

@ManuelOtto是的!究竟! – yavg

回答

1

有沒有簡單的方法來拖在畫布上繪製的東西,所以你必須存儲所有點的位置,並重新繪製整個c anvas。 事情是這樣的:

var points = [] 
var drag_point = -1 

$("#canvas").mousedown(function(e){ 
    var pos = getPosition(e) 
    drag_point = getPointAt(pos.x,pos.y) 
    if(drag_point==-1){ // no point at this position, add new point 
     drawCoordinates(pos.x,pos.y) 
     points.push(pos) 
    } 

}); 
$("#canvas").mousemove(function(e){ 
    if(drag_point!=-1){ // if currently dragging a point... 
     var pos = getPosition(e) 
     //...update points position... 
     points[drag_point].x = pos.x 
     points[drag_point].y = pos.y 
     redraw() // ... and redraw canvas 
    } 
}); 
$("#canvas").mouseup(function(e){ 
    drag_point = -1 
}); 

function getPointAt(x,y){ 
    for(var i=0;i<points.length;i++){ 
     if(Math.abs(points[i].x-x)<pointSize && Math.abs(points[i].y-y)<pointSize) // check if x,y is inside points bounding box. replace with pythagoras theorem if you like. 
      return i 
    } 
    return -1 // no point at x,y 
} 

function redraw(){ 
    var canvas = document.getElementById("canvas") 
    var ctx = canvas.getContext("2d"); 

    ctx.clearRect(0, 0, canvas.width, canvas.height); // clear canvas 

    for(var i=0;i<points.length;i++){ // draw all points again 
     drawCoordinates(points[i].x,points[i].y) 
    } 
} 

function getPosition(event){ 
    var rect = canvas.getBoundingClientRect(); 
    var x = event.clientX - rect.left; 
    var y = event.clientY - rect.top; 
    return {x:x,y:y} 
} 

function drawCoordinates(x,y){ 
    var ctx = document.getElementById("canvas").getContext("2d"); 

    ctx.fillStyle = "#ff2626"; // Red color 

    ctx.beginPath(); 
    ctx.arc(x, y, pointSize, 0, Math.PI * 2, true); 
    ctx.fill(); 
} 
+0

太棒了!這工作正常,請再提一個問題。我怎樣才能得到畫布上所有點的座標?感謝天才! http://jsfiddle.net/6uguqnxw/ – yavg

+0

所有點都存儲在「點」數組中。每個點都是這樣的對象{x:0,y:0} –

+0

你是最棒的!謝謝!你贏得了我想知道的最佳答案,如果從點1到點6加入一條線(假設你有10點)很容易 – yavg

0

進口 <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> 和使用jQuery拖動div..Example:

$('#divname').draggable(); 
+0

認爲他在談論拖動畫布上的繪製內容... –

+0

@ManuelOtto是的,我需要.. – yavg