问题
I am trying to introduce a grid function (to add/remove) a grid on a canvas. I pulled most of the following code:
var make_gr
id = function() {
var grid = new Kinetic.Layer();
var r = new Kinetic.Rect({
x: 0,
y: 0,
width: W,
height: H,
fill: 'transparent'
});
grid.add(r);
for (i = 0; i < w + 1; i++) {
var I = i * CELL_SIZE;
var l = new Kinetic.Line({
stroke: "black",
points: [I, 0, I, H]
});
grid.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]
});
grid.add(l2);
}
stage.add(grid);
};
to this fiddle, but it doesn't work. All I want is for a grid to be drawn at the base of the canvas - to allow people to fine tune the positioning of elements on the canvas. I also want to give the user the ability to remove the grid. Can anybody see what I have missed?
Many Thanks for any help!
回答1:
Your button click function is calling makeGrid() which is undefined.
Your function is called make_grid() so you need to change your click event from:
$d("body").on('click','#addGrid',function(){
makeGrid();
});
To:
$d("body").on('click','#addGrid',function(){
make_grid();
});
Once you do that, the grid appears. To remove it you can either use hide() remove() or destroy() on the grid layer that you created with make_grid(). Since you want to allow the user to hide/show the grid, I recommend using .hide().
Also note that you should only add the grid layer to the stage once. I suggest you call make_grid() when the stage is initialised, but hide the grid layer. Then with your two buttons just use .show() and .hide() to make the grid appear and disappear.
More info on remove vs destroy: What is the difference between remove and destroy in kinetic.js
来源:https://stackoverflow.com/questions/19659288/kineticjs-add-grid-to-canvas