Drag and Drop Multiple Objects in HTML5 Canvas

后端 未结 1 1820
隐瞒了意图╮
隐瞒了意图╮ 2021-01-01 05:13

I\'m trying to implement an application in which the user can drag and drop multiple objects inside a given area..I\'m using html5 canvas tag to implement this..When there i

1条回答
  •  一整个雨季
    2021-01-01 05:58

    When moving 1 (or more) shapes, the procedure is:

    Create objects that define each shape:

    // an array of objects that define different rectangles
    var rects=[];
    rects.push({x:75-15,y:50-15,width:30,height:30,fill:"#444444",isDragging:false});
    rects.push({x:75-25,y:50-25,width:30,height:30,fill:"#ff550d",isDragging:false});
    rects.push({x:75-35,y:50-35,width:30,height:30,fill:"#800080",isDragging:false});
    rects.push({x:75-45,y:50-45,width:30,height:30,fill:"#0c64e8",isDragging:false});
    

    In mousedown:

    • get the current mouse position
    • set the isDragging flag on any shape that is under the mouse
    • save the current mouse position

    In mousemove:

    • get the current mouse position
    • calculate how far the mouse has moved ( distance = newMousePosition-oldMousePosition )
    • add the distance to the position of any shape that isDragging
    • save the current mouse position
    • redraw the scene with shapes in their new positions

    In mouseup:

    • clear all isDragging flags

    Here's annotated code and a Demo: http://jsfiddle.net/m1erickson/qm9Eb/

    
    
    
     
    
    
    
    
    
    
    
        
    
    
    

    0 讨论(0)
提交回复
热议问题