JSFiddle - React, Tailwind, and code Playground
by alexb
HTML
<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="601" height="601"></canvas>
JavaScript
const canvas = new fabric.Canvas('c');
// Set up grid
const grid = 50;
const gridOptions = {
width: grid,
height: grid,
properties: {
fill: 'rgba(0,0,0,0.3)',
stroke: 'rgba(0,0,0,0.5)',
strokeWidth: 1,
},
};
// Add grid to canvas
const gridGroup = new fabric.Group([], {
left: 0,
top: 0,
selectable: false,
});
for (let i = 0; i < (canvas.width / grid); i++) {
for (let j = 0; j < (canvas.height / grid); j++) {
const rect = new fabric.Rect({
...gridOptions,
left: i * grid,
top: j * grid,
});
gridGroup.addWithUpdate(rect);
}
}
canvas.add(gridGroup);
// Load image onto canvas
const img = new Image();
img.src = 'https://i.imgur.com/UYiroys.jpg';
img.onload = function() {
const image = new fabric.Image(img, {
left: 100,
top: 100,
width: 250,
height: 250,
});
canvas.add(image);
};
// Enable dragging and snapping
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,
});
});