0

我是 Kintetic.js 的新手,我正在尝试做一个网格。宽度为 800 像素,高度为 400 像素。我希望正方形(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。这段代码的第一个问题是它非常慢,在网格出现之前我得到了 500 毫秒的延迟。但最糟糕的是,如果我在 cbox 上放置一个 mouseover 和 mouseout 事件来更改填充颜色,那么渲染速度真的很慢。我就是这样做的:

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

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

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

4

1 回答 1

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);​
于 2012-08-04T19:44:23.837 回答