修改网格高度/宽度

时间:2016-02-26 17:40:08

标签: javascript fabricjs

我正在开发一个项目,这是一个我喜欢的游戏的世界策划/建设者。我想让网格100 * 54.我一直在搞乱JSFiddle上的一些代码,我似乎无法得到我想要的东西。我希望网格方块的大小为16 * 16

var canvas = new fabric.Canvas('c', {
  selection: false
});
var grid = 50;


// create grid

for (var i = 0; i < (600 / grid); i++) {
  canvas.add(new fabric.Line([i * grid, 0, i * grid, 600], {
    stroke: '#ccc',
    selectable: false
  }));
  canvas.add(new fabric.Line([0, i * grid, 600, i * grid], {
    stroke: '#ccc',
    selectable: false
  }))
}

// add objects

canvas.add(new fabric.Rect({
  left: 100,
  top: 100,
  width: 50,
  height: 50,
  fill: '#faa',
  lockRotation: true,
  lockScalingX: true,
  lockScalingY: true,
  originX: 'left',
  originY: 'top',
  centeredRotation: true,
  hasControls: false
}));


// snap to grid

canvas.on('object:moving', function(options) {
  options.target.set({
    left: Math.round(options.target.left / grid) * grid,
    top: Math.round(options.target.top / grid) * grid
  });
});
canvas {
  border: 1px solid #ccc;
}
<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="600" height="600"></canvas>

1 个答案:

答案 0 :(得分:0)

这种方式有效: 网格是网格的像素大小。 您需要两个for循环来指示每个循环的行数。 for循环根据它经过的循环数生成网格。 (所以54表示54行。)

2000表示该行的像素长度。

工作代码:

&#13;
&#13;
var canvas = new fabric.Canvas('c', {
  selection: false
});
var grid = 16;


// create grid

for (var i = 0; i < 100; i++) {
  canvas.add(new fabric.Line([i * grid, 0, i * grid, 2000], {
    stroke: '#ccc',
    selectable: false
  })); // horizontal
}

for (var i = 0; i < 54; i++) {
  canvas.add(new fabric.Line([0, i * grid, 2000, i * grid], {
    stroke: '#ccc',
    selectable: false
  })); // vertical
}

// add objects

canvas.add(new fabric.Rect({
  left: 16,
  top: 16,
  width: 16,
  height: 16,
  fill: '#faa',
  lockRotation: true,
  lockScalingX: true,
  lockScalingY: true,
  originX: 'left',
  originY: 'top',
  centeredRotation: true,
  hasControls: false
}));

// add objects

canvas.add(new fabric.Rect({
  left: 16,
  top: 16,
  width: 16,
  height: 16,
  fill: '#faa',
  lockRotation: true,
  lockScalingX: true,
  lockScalingY: true,
  originX: 'left',
  originY: 'top',
  centeredRotation: true,
  hasControls: false
}));

// snap to grid

canvas.on('object:moving', function(options) {
  options.target.set({
    left: Math.round(options.target.left / grid) * grid,
    top: Math.round(options.target.top / grid) * grid
  });
});
&#13;
canvas {
  border: 1px solid #ccc;
}
&#13;
<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="1600px" height="865px" ></canvas>
&#13;
&#13;
&#13;