Raphael - Drawing shapes with mouse

后端 未结 3 2166
忘了有多久
忘了有多久 2021-02-08 21:24

What would be the best way to draw a rectangle or circle for that matter using your mouse ?

I just started looking at raphael and it seems I should use, drag? Or moused

3条回答
  •  逝去的感伤
    2021-02-08 22:07

    I would use mousedown and mouseup events on your canvas/paper. On mouse down you should store the x and y positions of the mousedown, then on mouseup you should use the current mouse positions to calculate width and height.

    Here is an example, bear in mind thought that I am using JQuery to calculate the mouse positions (if this is not available for you, then you should find another way to get the mouse offsets)

    //global variables
    var mouseDownX = 0;
    var mouseDownY = 0;
    
    //register events on document load
    paper.mousedown(OnMouseDown);
    paper.mouseup(OnMouseUp);
    
    function OnMouseDown(e){
       var offset = $("#Canvas").offset();//This is JQuery function
       mouseDownX = e.pageX - offset.left;
       mouseDownY = e.pageY - offset.top;
    }
    
    function OnMouseUp(e){
       var offset = $("#Canvas").offset();//This is JQuery function
       var upX = e.pageX - offset.left;
       var upY = e.pageY - offset.top;
    
       var width = upX - mouseDownX;
       var height = upY - mouseDownY;
    
       DrawRectangle(mouseDownX, mouseDownY, width, height);
    }
    
    function DrawRectangle(x, y, w, h){
       var element = paper.rect(x, y, w, h);
       element.attr({
                fill: "#FFF",
                stroke: "#F00"
            });
    }
    

    Hope that helps

提交回复
热议问题