[英]Kinetic.js – creating a grid
I'm new to Kintetic.js and I'm trying to do a grid. 我是Kintetic.js的新手,正在尝试创建网格。 The width is 800px and the height is 400px.
宽度为800像素,高度为400像素。 And I want squares (20x20) to cover that area.
我想要正方形(20x20)覆盖该区域。 Every square has a 1px border.
每个正方形都有一个1px的边框。 So something like this:
所以像这样:
var box = new Kinetic.Rect({
width: 20,
height: 20,
fill: 'transparent',
stroke: 'rgba(0, 0, 0, 0.02)'
});
And to fill the canvas, I have a crappy for-loop like this: 为了填充画布,我有一个糟糕的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 is a Kinetic.Layer. this.grid是一个Kinetic.Layer。 The first problem with this code is that it is very slow and I get like a 500ms delay before the grid shows up.
这段代码的第一个问题是它非常慢,在显示网格之前我有500ms的延迟。 But the worst thing is that if I put an mouseover and mouseout event on the cbox to change the fill color, that renders really really slow.
但是最糟糕的是,如果我在cbox上放置一个mouseover和mouseout事件来更改填充颜色,则渲染速度真的很慢。 This is how I do it:
这是我的方法:
cbox.on('mouseover', function () {
this.setFill('black');
self.grid.draw();
});
cbox.on('mouseout', function () {
this.setFill('transparent');
self.grid.draw();
});
So my question is how can I improve the code and performance of this? 所以我的问题是如何改善此代码和性能?
How about to make grid with lines and use one rect for cursor highlighting? 如何用线制作网格并使用一个矩形来突出显示光标? Here i wrote the example for you: http://jsfiddle.net/e_aksenov/R72Xu/30/
在这里,我为您编写了示例: 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.