2012-03-27 91 views

回答

0

下面的鏈接和代碼。 http://html5.litten.com/how-to-drag-and-drop-on-an-html5-canvas/

<html> 
    <head> 
    </head> 
    <body> 
    <section> 
    <div> 
    <canvas id="canvas5" height="300" width="400"> This text is displayed if your browser does not support HTML5 Canvas. </canvas> 
    </div> 
    <script type="text/javascript"> 
    var canvas5; 
    var ctx5; 
    var x5 = 75; 
    var y5 = 50; 
    var dx5 = 5; 
    var dy5 = 3; 
    var WIDTH5 = 400; 
    var HEIGHT5 = 300; 
    var dragok = false; 
    function rect(x,y,w,h) { 
    ctx5.beginPath(); 
    ctx5.rect(x,y,w,h); 
    ctx5.closePath(); 
    ctx5.fill(); 
    } 
    function clear() { 
    ctx5.clearRect(0, 0, WIDTH5, HEIGHT5); 
    } 
    function init() { 
    canvas5 = document.getElementById("canvas5"); 
    ctx5 = canvas5.getContext("2d"); 
    return setInterval(draw5, 10); 
    } 
    function draw5() { 
if(x5>10 && x5<350 && y5>10 && y5<350) 
{ 
    clear(); 
    ctx5.fillStyle = "#FAF7F8"; 
    rect(0,0,WIDTH5,HEIGHT5); 
    ctx5.fillStyle = "#444444"; 
    rect(x5 - 15, y5 - 15, 30, 30); 
    } 
    } 
    function myMove(e){ 
    if (dragok){ 
    x5 = e.pageX - canvas5.offsetLeft; 
    y5 = e.pageY - canvas5.offsetTop; 
    } 
    } 
    function myDown(e){ 
    if (e.pageX < x5 + 15 + canvas5.offsetLeft) 
    if (e.pageX > x5 - 15 + canvas5.offsetLeft) 
    if (e.pageY < y5 + 15 + canvas5.offsetTop) 
    if (e.pageY > y5 -15 + canvas5.offsetTop){ 
    x5 = e.pageX - canvas5.offsetLeft; 
    y5 = e.pageY - canvas5.offsetTop; 
    dragok = true; 
    canvas5.onmousemove = myMove; 
    } 
    } 
    function myUp(){ 
    dragok = false; 
    canvas5.onmousemove = null; 
    } 
    init(); 
    canvas5.onmousedown = myDown; 
    canvas5.onmouseup = myUp; 
    </script> 
    </section> 
    </body> 
    </html> 
+0

Maneesh謝謝,但我想是這樣給出的圖像 - 圖像,鷹剪貼畫是不是在畫布上 移出定義的邊界假設我們有固定的邊界剪貼畫開始點(10,10)到( 350,350) http://plus.google.com/u/0/photos/109906204570243538818/albums/5724543242938487617 – 2012-03-27 11:53:52

+0

您可以使用draw5函數中的條件來執行此操作... if(x5> 10 && x5 <350 && y5> 10 && y5 < 350)..編輯答案。 – Maneesh 2012-03-27 12:11:58

+0

好的會的。再次感謝 – 2012-03-27 13:33:51

0

如果你想就如何使對象可拖動的HTML5 Canvas中我寫的教程有很多的解釋here乾淨的教程。

對於您在畫布上繪製的每個對象,您可能還需要給它一些「限制邊界」,如limitX,limitY,limitWidth,limitHeight等。然後在拖動時需要確保它仍然在這些範圍內。如果它超出界限,你只會強迫它靠近它試圖被拖出的那一邊。