Performance slow with kineticjs

前端 未结 3 1389
无人共我
无人共我 2021-01-07 05:42

Sorry if this question was asked already, I\'ve tried to find it by couldn\'t.

I have a canvas that should eventually show about 400-500 rectangles 20-30 pixels heig

3条回答
  •  既然无缘
    2021-01-07 06:31

    Alright, this was a good challenge. I thought that the problem was in the shape events but the improvement there were ever so small.

    The events in KineticJS are applied to the specific on screen shapes by searching through the co-ordinates of the models until one matches the current mouse co-ordinates. So by having only one layer, we increase the size of the array to search.

    The fix is to use many layers. I added a layer for every row.

    Some of the other changes in the code below are:

    1. Don't move shapes between layers. It causes an array splice and an index shift.
    2. Use the relative move(x,y) method instead of setX() setY() methods for small shifts.
    3. The animation layer concept you read in a tutorial is used for doing actual animation on a timed frame interval. We are just doing a normal shape move on an event.
    4. Minor JS improvement; When returning an object to hide private data and methods, don't use new for creating an object.

    Page

    
    

    Code

    seatMap.Map = function (params) {
    var stage = new Kinetic.Stage({
        container: params.container,
        width: params.width,
        height: params.height
    });
    
    var addSeat = function (object, layer) {
        object.seat.layer = layer;
        layer.add(object.seat);     
    };
    
    var refresh = function () {
        mainLayer.draw();
    };
    
    var createLayer = function() {
        var layer = new Kinetic.Layer();
        stage.add(layer);
        return layer;
    };
    return {
        createLayer : createLayer,
        refresh: refresh,
        addSeat: addSeat
    };
    }
    
    seatMap.Seat = function (params) {
    
    var seatType = params.seatType == null ? seatMap.seatTypes.economy : params.seatType;
    
    var seat = new Kinetic.Rect({
        width: seatType.width,
        height: seatType.height,
        x: params.x,
        y: params.y,
        fill: seatType.fill,
        stroke: seatType.stroke,
        strokewidth: seatType.strokewidth,
        cornerRadius: seatType.cornerRadius,
        listening: true
    });
    seat.staticXPosition = params.x;
    seat.staticYPosition = params.y;
    
    seat.on('mouseover', function (event) {
        event.shape.move(-3,-3);
        event.shape.layer.draw();
    });
    seat.on('mouseout', function (event) {
    
        event.shape.move(3,3);
        event.shape.layer.draw();
    });
    
    return {
        seat: seat,
    };
    }
    

提交回复
热议问题