gpt4 book ai didi

Fabricjs - 如何通过键盘移动选定的对象

转载 作者:行者123 更新时间:2023-12-02 08:13:07 25 4
gpt4 key购买 nike

我想用键盘移动选中的对象,因为可以更准确地移动,我不知道怎么做。

最佳答案

这是我使用左/上/右/下键移动选定对象/组的简单实现:

https://jsfiddle.net/milanhlinak/4fofjzvm/

<!DOCTYPE html>
<html>

<head>
<script type="text/javascript" src="lib/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="lib/fabric.min.js"></script>
</head>

<body>

<canvas id="canvas" style="border: 1px solid #cccccc"></canvas>

<script>
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.Rect({
left: 300,
top: 300,
width: 50,
height: 50,
fill: '#afa'
}));

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:
activeGroup.setTop(activeGroup.getTop() + STEP);
break;
}
activeGroup.setCoords();
canvas.renderAll();
console.log('selected group was moved');
} else {
console.log('no object selected');
}

}
</script>

</body>

</html>

关于Fabricjs - 如何通过键盘移动选定的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44320104/

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