Kinetic.js - 创建一个网格

时间:2012-08-03 18:10:45

标签: javascript html5-canvas kineticjs

我是Kintetic.js的新手,我正在尝试做网格。宽度为800px,高度为400px。我想要方块(20x20)来覆盖那个区域。每个方格都有1px边框。所以像这样:

var box = new Kinetic.Rect({
  width: 20,
  height: 20,
  fill: 'transparent',
  stroke: 'rgba(0, 0, 0, 0.02)'
});

为了填充画布,我有一个糟糕的for循环:

for (var i = 0; i <= this.field.getWidth(); i = i + 20) {
  for (var i2 = 0; i2 <= this.field.getHeight(); i2 = i2 + 20) {
    var cbox = box.clone({x: i, y: i2});
    this.grid.add(cbox);
  }
}

this.grid 是一个Kinetic.Layer。这段代码的第一个问题是它非常慢,在网格显示之前我得到了500ms的延迟。但最糟糕的是,如果我在cbox上放置一个mouseover和mouseout事件来改变填充颜色,那真的很慢。我就是这样做的:

cbox.on('mouseover', function () {
  this.setFill('black');
  self.grid.draw();
});

cbox.on('mouseout', function () {
  this.setFill('transparent');
  self.grid.draw();
});

所以我的问题是如何改善这个代码和性能?

1 个答案:

答案 0 :(得分:5)

如何使用直线制作网格并使用一个矩形进行光标突出显示? 在这里我为你写了这个例子: http://jsfiddle.net/e_aksenov/R72Xu/30/

var CELL_SIZE = 35,
w = 4,
h = 5,
W = w * CELL_SIZE,
H = h * CELL_SIZE;

var make_grid = function(layer) {
var back = new Kinetic.Rect({
    x: 0,
    y: 0,
    width: W,
    height: H,
    fill: "yellow"
});
layer.add(back);
for (i = 0; i < w + 1; i++) {
    var I = i * CELL_SIZE;
    var l = new Kinetic.Line({
        stroke: "black",
        points: [I, 0, I, H]
    });
    layer.add(l);
}

for (j = 0; j < h + 1; j++) {
    var J = j * CELL_SIZE;
    var l2 = new Kinetic.Line({
        stroke: "black",
        points: [0, J, W, J]
    });
    layer.add(l2);
}
    return back; //to attach mouseover listener
};

var cursor_bind = function(layer, grid_rect, rect) {

grid_rect.on('mouseover', function(e) {
    var rx = Math.floor(e.x / CELL_SIZE);
    var ry = Math.floor(e.y / CELL_SIZE);
    rect.setPosition(rx * CELL_SIZE, ry * CELL_SIZE);
    layer.draw();
});
};

var stage = new Kinetic.Stage({
container: "kinetic",
width: 800,
height: 600,
draggable: true
});

var layer = new Kinetic.Layer();

var rect = new Kinetic.Rect({
x: 0,
y: 0,
width: CELL_SIZE,
height: CELL_SIZE,
fill: "#00D2FF",
stroke: "black",
strokeWidth: 4
});

var gr = make_grid(layer);
cursor_bind(layer, gr, rect);

// add the shape to the layer
layer.add(rect);

// add the layer to the stage
stage.add(layer);​