Better way to draw a quadratic Curve in KineticJS?

651 Views Asked by At

I am writing an app in which I have to draw a lot of draggable quadratic curves.

I am using Kinetic.Shape for this (KineticJS 4.4.3).

Since the performance is not great I tried to analyze and optimize the code and found out that the drawFunc function is executed twice. Look at the attached Demo Code.

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

var curveLayer = new Kinetic.Layer();

var line = new Kinetic.Shape({
    drawFunc: function (canvas) {
        console.log("drawFunc executed");
        var context = canvas.getContext();
        context.beginPath();
        context.moveTo(10, 10);
        context.quadraticCurveTo(95, 100, 200, 10);
        canvas.stroke(this);
    },
    strokeWidth: 10
});

curveLayer.add(line);
stage.add(curveLayer);

If you run the script there will be 2 times "drawFunc executed" in the console.

I do not understand why and I ask myself if there is any better way to do it.

The Link to the Fiddle: http://jsfiddle.net/solitud/ZpU4J/9/

The Link to my project: http://modulargrid.net/e/patches/view/92

1

There are 1 best solutions below

3
On

KineticJS always creates a non-visible buffer canvas that it uses for drags, etc.

You are seeing drawFunc execute once for that buffer canvas and once for your visible canvas.

No way to eliminate that 2X drawing.

Looking at your project link, I'm guessing that the user creates connections into various receptors by visually dragging the plugs. No way to make that more efficient.

But, once any connection is complete, you can greatly speed redrawing of that connector by caching it to an image: connector1.toImage( ... );

Redrawing your image-cached "connectors" create much less performance penalty than redrawing quad-beziers.