Search code examples
javascriptlinekineticjs

KineticJS - Creating a draggable line using mouse


I'm trying to create a line within a bounded area that can also be dragged around once it has been drawn on the layer. Although there are solutions for creating lines dynamically - http://jsfiddle.net/42RHD/65/, I also need them to be draggable around the canvas.

Setting

draggable: true

does not work. I'm guessing it's because we are overriding the mouse down and mouse up events? Here's my attempt with a different approach, which also doesn't work -

<body>
<div id="container"></div>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.0.1.min.js"></script>
<script defer="defer">
    var x1, y1, x2, y2

    var stage = new Kinetic.Stage({
        container: 'container',
        width: 700,
        height: 700
    });

    var layer = new Kinetic.Layer();

    var line = new Kinetic.Line({
        y: 0,
        points: [x1, y1, x2, y2],
        stroke: 'black',
        strokeWidth: 5,
        lineCap: 'round',
        lineJoin: 'round',
        draggable: true
    });

    var bounds = new Kinetic.Rect({
        x: 50,
        y: 50,
        width: 600,
        height: 600,
        fill: 'white',
        stroke: 'black',
        strokeWidth: 4
    });

    layer.add(bounds);
    layer.add(line);
    stage.add(layer);

    bounds.on('mousedown', function() {
        var start = stage.getPointerPosition();
        x1 = start.x - 190;
        y1 = start.y - 40;
    });

    bounds.on('mouseup', function() {
        var end = stage.getPointerPosition();
        x2 = end.x - 190;
        y2 = end.y - 40;
        line.draw();
    });
</script>


Solution

  • Made the switch to FabricJS. The following fiddle shows what I wanted to do:

    http://jsfiddle.net/RDqTd/27/

    updateComplexity();
    

    takes care of it.