Joshua
Joshua

Reputation: 1270

Speeding up my KineticJS drawing canvas on mobile

I looking to use KineticJS as drawing canvas and it works very on desktop browsers, but is very sluggish on mobile browsers. Right now I'm just continuously calling draw on the layer as the mouse is moving and setting the new points to the marker line.

What could I do to optimize the speed on this a little bit more without loosing the smoothness of drawing?

var stage;
var input;
var marker;
var points = [];

function initialize() {
    stage = new Kinetic.Stage({
    container: 'container',
        width: $(window).width(),
        height: $(window).height()
    });

    input = new Kinetic.Layer();
    stage.add(input);
    marker = new Kinetic.Line({
        stroke: 'red',
        strokeWidth: 16,
        lineCap: 'round',
        lineJoin: 'round'
    });
    input.add(marker);

    stage.on('mousedown touchstart', handleMouseDown);
    stage.on('mouseup touchend', handleMouseUp);
}

function handleMouseDown() {
    points = [];
    stage.on('mousemove touchmove', handleMouseMove);
}

function handleMouseMove() {
    points.push(stage.getPointerPosition());
    marker.setAttr('points', points);
    input.draw();
}

function handleMouseUp() {
    stage.off('mousemove touchmove');
}

Upvotes: 1

Views: 563

Answers (1)

markE
markE

Reputation: 105015

You can improve performance by de-linking the draw's from the mousemoves.

Since mousemove is being done often and repeatedly, just gather the points in handleMouseMove.

function handleMouseMove() {
    points.push(stage.getPointerPosition());
}

Then set up a timer loop to do the drawing as a batch.

Preferably use requestAnimationFrame but for some mobile you might have to use setTimeout

This will significantly reduce the number of expensive input.draw's required.

    // thank you Paul Irish for this RAF/setTimeout shim

    window.requestAnimFrame = (function(callback) {
      return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
      function(callback) {
        window.setTimeout(callback, 1000 / 60);
      };
    })();

// draw the points in a batch when RAF fires 

function batchDraw() {
    marker.setAttr('points', points);
    input.draw();
    requestAnimFrame(batchDraw);
}

Upvotes: 1

Related Questions