KineticJS, can I just redraw one shape? (drawing o

2019-09-02 18:21发布

In KineticJS, I would like to add a shape to a layer, and only redraw the most recently added shape, rather than all shapes in that layer. Is this possible? Or maybe some workaroud?

(.draw() function redraws all the child nodes on the layer)

More details on my situation:

I have a layer on which I want to draw a line which traces the movement of an shape across the screen during animation.

       //create my shapes first
       var myShape = new Kinetic.Circle({config});
       //myShape gets its own layer, shapeLayer
       var traceLine= new Kinetic.Line({x: myShape.getX() , y: myShape.getY()});
       //traceLine gets its own layer, traceLayer

During animation I execute this code to update and redraw the line:

       //during animation loop
       var points = traceLine.getPoints();
       points.push({x: myShape.getX() , y: myShape.getY()});
       traceLine.setPoints(points);   // this is currently the most efficient method I can think of
       traceLayer.draw();  // redraw the line
       shapeLayer.draw(); // the shape gets redrawn as well

This works well for a short while, but as time goes on I am getting a large array of points and the time to redraw the line is getting longer.

What I would like to do is draw a new line onto the layer during each loop of the animation, making it segmented. Like so:

       var traceLine= new Kinetic.Line({x: myShape.getX() , y: myShape.getY(), x: myShape.getX()+1, y: myShape.getY()+1}); // draw as a point
       traceLayer.add(traceLine);
       traceLayer.draw();  //this slows it down as all lines get redrawn.

But the .draw() function redraws all the child nodes on the layer, which is not any more efficient or faster.

Sorry I didn't put up a jsfiddle, cause my code is very long, but if you need more details just let me know.

1条回答
我想做一个坏孩纸
2楼-- · 2019-09-02 18:29

This question was related to the idea of not wanting to erase any previous objects on the screen, but not wanting to redraw any of them, basically to just draw one new item and show the layer. I solved this by just drawing directly onto the layer.

 var traceLayerDraw = traceLayer.getCanvas();
 var context = traceLayerDraw.getContext('2d'); 
 context.beginPath();
 context.moveTo(xBefore, yBefore);
 context.lineTo(newX, newY);
 context.stroke();

So I just took the layer and drew onto it using before and after values of the object I want to draw in a new location.

I did have to also set the layer to 'clearBeforDraw: false' as an attribute of the layer.

查看更多
登录 后发表回答