gpt4 book ai didi

javascript - 修改网格高度/宽度

转载 作者:行者123 更新时间:2023-11-28 06:19:28 26 4
gpt4 key购买 nike

我正在开发一个项目,该项目是我喜欢的游戏的世界规划/构建器。我想让网格为 100 * 54。我一直在 JSFiddle 上搞乱一些代码,但我似乎无法得到我想要的。我希望网格方 block 的大小为 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>

最佳答案

其工作原理:网格是网格的大小(以像素为单位)。您需要两个 for 循环来指示每个循环有多少行。for 循环根据其经过的循环次数生成网格。 (所以 54 意味着 54 行。)

2000 表示线条的长度(以像素为单位)。

工作代码:

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
});
});
canvas {
border: 1px solid #ccc;
}
<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="1600px" height="865px" ></canvas>

关于javascript - 修改网格高度/宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35658272/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com