Kineticjs: как использовать Pen Tool с помощью Kineticjs?

Я хотел бы использовать инструмент пера (например, фотомагазин) с помощью кинетики, я понятия не имею, как этого добиться.

можно или нет?. Если возможно, помогите найти решение.

Я использую файлы кинетики-v5.0.1.min.js и кинетики-v5.0.1.js.

Заранее спасибо.


person Siva    schedule 27.05.2014    source источник


Ответы (2)


Вот полное решение.

Рабочая демонстрация: http://jsfiddle.net/JSdc2/LjJ8W/

 document.body.addEventListener( 'mousedown', startListening, false );

    // -- /init


    // add ins for testing

    var stage = new Kinetic.Stage({

        width: window.innerWidth - 30,
        height: window.innerHeight - 70,
        container: 'container'

    });

    var freeHandLayer = new Kinetic.Layer({

        x:0,
        y:0,
        width: window.innerWidth/2,
        height: window.innerHeight/2

    });

    var background = new Kinetic.Rect({

        width: window.innerWidth - 30,
        height: window.innerHeight - 70,
        fill: '#DDDDDD'

    });

    freeHandLayer.add( background );
    stage.add( freeHandLayer );

    // -- /add ins


  var ctx = freeHandLayer.getContext('2d');

    // ------- freeHand Functions
    // thanks to http://nick.zoic.org/

    function draw_marker(x, y, r) {

        ctx.beginPath();
        ctx.arc(x, y, r, 0, Math.PI*2);
        ctx.closePath();
        ctx.fillStyle = "#0F0";
        ctx.fill();

    }

    function draw_segment(x1, y1, x2, y2) {

        ctx.beginPath();
        ctx.moveTo(x1, y1);
        ctx.lineTo(x2, y2);
        ctx.strokeStyle = "#0F0";
        ctx.stroke();
        ctx.closePath();

    }

    // -----

    var pos, ox, oy, xys, nx, ny, dx, dy, dd;
    var points = [];
    var xnums = [];
    var ynums = [];


    function startListening() {

        points=[]; // clear array 
        xnums=[];
        ynums=[];

        pos = stage.getPointerPosition();

        ox = pos.x;
        oy = pos.y;
        xnums[0] = ox;
        ynums[0] = oy;

        document.body.removeEventListener( 'mousedown', startListening );
        document.body.addEventListener( 'mousemove', handleMovement, false );

    }

    function handleMovement() {

        document.body.addEventListener('mouseup', finalizeSpline, false );

         pos = stage.getPointerPosition();
         nx = pos.x;
         ny = pos.y;

         dx = nx - ox;
         dy = ny - oy;
         dd = Math.sqrt(dx*dx + dy*dy);

        if (dd > 10) {
            draw_segment(ox, oy, nx, ny);
            xnums.push(nx);
            ynums.push(ny);
            ox = nx;
            oy = ny;
        }
    }

    var ID = 0;
    var customShape = [];

    function finalizeSpline() {

        ID++;

        document.body.removeEventListener('mousemove', handleMovement );
        document.body.removeEventListener('mouseup', finalizeSpline );

        for ( var i = 0; i < xnums.length; i++ ) {

            points.push (xnums[ i ]);
            points.push (ynums[ i ]);

        }

        // Create a Group for the new shape to live inside

        customShape[ID] = new Kinetic.Group({

            x: 0,
            y: 0,
            rotationDeg: 0

         });

        customShape[ID].id = 'L06customShape' + ID;
        customShape[ID].attrs.id = 'L06customShape' + ID;
        customShape[ID].selectable = true; 
        customShape[ID].selectStyle = "group" ;
        customShape[ID].colorable = true;
        customShape[ID].colorStyle = "single" ;
        customShape[ID].description = "A custom shape." ;
        customShape[ID].difficulty = 1;

        // Create the shape from user input

        var spline = new Kinetic.Line({

            id:'L06spline' + ID,
            points: points, // uses the points we collected from user pointer movement
            tension: 0, // TO DO: don't like the range Kinetic offers 0 to 1, create something better.
            closed: false,
            fill: '#ccc',
            draggable: true

          });

        // add some tweaks

        customShape[ID].on('mousedown touchstart', function( e ) { signals.mouseDown.dispatch( this, e ); });
        customShape[ID].on('mouseup touchend', function( e ) { signals.mouseUp.dispatch( this, e ); });

        customShape[ID].add( spline );
        customShape[ID].className = 'Blob';

        freeHandLayer.add( customShape[ID] );
    document.body.addEventListener( 'mousedown', startListening, false );

    }

       function getPointerPos( e ) {

        var position = ctx.getBoundingClientRect();

        return {

            x: e.clientX - position.left,
            y: e.clientY - position.top

        };
    }
person JSdc    schedule 29.05.2014
comment
Ах да, и если вы считаете, что это слишком «дергано» и недостаточно плавно, измените строку, которая говорит if (dd › 10) { на меньшее число. Эти 10 — это пространство между собранными точками экрана, поэтому, если вы не переместите хотя бы 10 пикселей, ничего не будет нарисовано. Так, например, установите его на 5, линия станет намного более гладкой. - person JSdc; 29.05.2014
comment
О, подождите, если вы имеете в виду инструмент «перо», такой как тот, который позволяет редактировать узлы с помощью маленьких ручек, вам придется объединить что-то вроде того, что я написал выше, и добавить такую ​​функциональность: html5canvastutorials.com/labs/ - person JSdc; 29.05.2014
comment
Теоретически вы можете посмотреть на этот код, который все еще показывает «дескрипторы» и сделать их перетаскиваемыми. nick.zoic.org/html5/< /а> - person JSdc; 29.05.2014
comment
спасибо JSDC. это любой момент, как сделать то же самое в кинетическом слое - person Siva; 02.06.2014

Что вы пробовали? Что вы нашли после поиска? В любом случае вам придется прослушивать события мыши на сцене, а затем рисовать Kinetic.Line. Эти два вопроса о Stackoverflow должны помочь вам, если вы их не видели.

KineticJS — рисование линий с помощью мыши

Kinetic.js — рисуйте линию от руки, следуя за указателем мыши

person Sahar Ch.    schedule 27.05.2014