Search code examples
javascriptjqueryhtmljquery-uijquery-ui-touch-punch

Draggable divs leaving a line trail when dragged, possible?


I'm currently trying to make a sort of online coach tactic board where you drag around divs posing as players to show a lineup or a specific tactic. I'm using Touch Punch for the dragging and it works well, on PCs, tablets and smarthpones (the two last ones being the target platforms).

What i would like to try and implement now is when you press a button lines start to be drawn in the trail after the players when dragged, so a pattern of how a specific player should run. Meaning you would first place players in starting positions, then start the line trail with a button, then start dragging them around in the running patterns so that is shown.

I currently have drawing of lines done in a <canvas>, but it means you drag the lines separate of dragging the players, which sometimes gets crowded and its easy to start dragging a div instead of starting to draw a line starting next to a div, especially on a touchscreen.

Anyone have any idea if this would be possible?


Solution

  • Thank you raam86, never imagined it would have been this simple.

    This is how i solved it in case someone comes down this road:

    $( "[id^=home]" ).draggable({
            // options...
            start: function(event,ui){
                context.strokeStyle = 'Blue';
                $( this ).addClass("dragging");
                if (drawWhenDragging){
                    context.beginPath();
                    context.moveTo(ui.position.left+$(this).width()/2, ui.position.top+$(this).width()/2);
                }
            },
            drag: function(event,ui){
                $( this ).addClass("dragging");
                if (drawWhenDragging){
                    context.lineTo(ui.position.left+$(this).width()/2, ui.position.top+$(this).width()/2);
                    context.stroke();
                }
            },
            stop: function(event,ui){
                $( this ).removeClass("dragging");
                if (drawWhenDragging){
                    context.closePath();
                }
            }
        });