Question

I just updated Kinetic JS from 4.3.3 to 5.1, used the following to draw a circle, centered at two lines crossing:

    circle1.setDrawHitFunc(function (canvas) {
        var context1 = canvas.getContext();
        var centerX1 = blueLine1.getPosition().x;
        centerY1 = greenLine1.getPosition().y;
        context1.beginPath();
        context1.arc(centerX1, centerY1, this.getRadius(), 0, 2 * Math.PI, false);
        context1.closePath();
        canvas.fillStroke(this);
        currentX = canvas.width / 2;
        currentY = canvas.height / 2;
    });

I get the following error:

Object doesn't support property or method 'getContext' 

I also get an error using stage1.getDragLayer().afterDraw as in my old example http://jsfiddle.net/m1erickson/cgF8y/

Était-ce utile?

La solution

The syntax of KineticJS has changed a great deal since V4.3.3.

Here's the new syntax for setting the hit function:

(Note that you're now given a context instead of a canvas as a parameter)

myShape.hitFunc( function(context){ ... } );

[ Addition to answer to refactor your code to work in KineticJS V5.1 ]

A working Demo: http://jsfiddle.net/m1erickson/2QG5W/

enter image description hereenter image description here

KineticJS now has a dragmove event which lets you respond every time your greenLine or blueLine is dragged.

This means you can:

  • Listen for dragmove on the green line and automatically reposition the circle vertically.

  • Listen for dragmove on the blue line and automatically reposition the circle horizontally.

This is much simpler than the way it had to be done in version4!

Here's how:

// reposition the circle vertically 
// every time the green line is dragged vertically

GreenLine1.on('dragmove',function(){
    circle1.y(GreenLine1.y()+GreenLine1.points()[1]);
    layer.draw();
});


// reposition the circle horizontally 
// every time the blue line is dragged horizontally

BlueLine1.on('dragmove',function(){
    circle1.x(BlueLine1.x()+BlueLine1.points()[0]);
    layer.draw();
});

One other thing

You can set a dragBoundFunc to keep the user from dragging your green line horizontally and keep the user from dragging your blue line vertically.

Here's how:

// save the X position of the green line

GreenLine1.fixedX=GreenLine1.x();

// let the user drag the green line vertically
// but not horizontally

GreenLine1.dragBoundFunc(function(pos){
    pos.x=GreenLine1.fixedX;
    return(pos);
});



// save the X position of the green line

BlueLine1.fixedY=BlueLine1.y();

// let the user drag the blue line horizontally
// but not vertically

BlueLine1.dragBoundFunc(function(pos){
    pos.y=BlueLine1.fixedY;
    return(pos);
});        
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top