JSFiddle - React, Tailwind, and code Playground
by Anuraj MS
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.1/fabric.min.js"></script>
<canvas id="canvas" style="border: 1px solid #cccccc"></canvas>
JavaScript
const STEP = 10;
var Direction = {
LEFT: 0,
UP: 1,
RIGHT: 2,
DOWN: 3
};
var canvas = new fabric.Canvas('canvas', {
width: 500,
height: 500,
});
canvas.add(new fabric.Rect({
left: 100,
top: 100,
width: 50,
height: 50,
fill: '#faa'
}));
canvas.add(new fabric.Circle({
left: 300,
top: 300,
radius: 25,
fill: '#afa'
}));
canvas.add(new fabric.IText('Hello world'));
fabric.util.addListener(document.body, 'keydown', function(options) {
if (options.repeat) {
return;
}
var key = options.which || options.keyCode; // key detection
if (key === 37) { // handle Left key
moveSelected(Direction.LEFT);
} else if (key === 38) { // handle Up key
moveSelected(Direction.UP);
} else if (key === 39) { // handle Right key
moveSelected(Direction.RIGHT);
} else if (key === 40) { // handle Down key
moveSelected(Direction.DOWN);
}
});
function moveSelected(direction) {
var activeObject = canvas.getActiveObject();
var activeGroup = canvas.getActiveGroup();
if (activeObject) {
switch (direction) {
case Direction.LEFT:
activeObject.setLeft(activeObject.getLeft() - STEP);
break;
case Direction.UP:
activeObject.setTop(activeObject.getTop() - STEP);
break;
case Direction.RIGHT:
activeObject.setLeft(activeObject.getLeft() + STEP);
break;
case Direction.DOWN:
activeObject.setTop(activeObject.getTop() + STEP);
break;
}
activeObject.setCoords();
canvas.renderAll();
console.log('selected objects was moved');
} else if (activeGroup) {
switch (direction) {
case Direction.LEFT:
activeGroup.setLeft(activeGroup.getLeft() - STEP);
break;
case Direction.UP:
activeGroup.setTop(activeGroup.getTop() - STEP);
break;
case Direction.RIGHT:
activeGroup.setLeft(activeGroup.getLeft() + STEP);
break;
case Direction.DOWN:
...