我正在开发使用fabric js创建形状的项目。我可以根据fabric js文档创建所有形状。
我遇到一个问题,即在用户拖动的形状下方创建一个形状。
请找到下面的小提琴,以便更好地理解,
{{1}}
{{1}}
这是fiddle
答案 0 :(得分:1)
$(document).ready(function() {
//Getting the canvas
var canvas = new fabric.Canvas("canvas");
var rect, isMouseDown = false;
$('#selection').click(function() {
canvas.selection = true;
changeStatus(true);
//remove mouse event
canvas.off('mouse:down', onMouseDown);
canvas.off('mouse:move', onMouseMove);
canvas.off('mouse:up', onMouseUp);
})
function changeStatus(value) {
canvas.forEachObject(function(obj) {
obj.selectable = value;
})
canvas.renderAll();
}
$('#rectangle').click(function() {
canvas.selection = false;
changeStatus(false);
//register mouse event
canvas.on('mouse:down', onMouseDown);
canvas.on('mouse:move', onMouseMove);
canvas.on('mouse:up', onMouseUp);
});
function onMouseDown(event) {
//Defining the procedure
isMouseDown = true;
var pointer = canvas.getPointer(event.e);
//Creating the rectangle object
rect = new fabric.Rect({
left: pointer.x,
top: pointer.y,
width: 0,
height: 0,
stroke: 'red',
strokeWidth: 3,
selectable: false,
fill: ''
});
canvas.add(rect);
}
function onMouseMove(event) {
// Defining the procedure
if (!isMouseDown) {
return;
}
var pointer = canvas.getPointer(event.e);
rect.setWidth(Math.abs((pointer.x - rect.get('left'))));
rect.setHeight(Math.abs((pointer.y - rect.get('top'))));
canvas.renderAll();
}
function onMouseUp() {
//alert("mouse up!");
rect.setCoords();
isMouseDown = false;
}
});

canvas {
border: 2px dotted green;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js" charset="utf-8"></script>
<script src="https://code.jquery.com/jquery-3.2.1.js" charset="utf-8"></script>
<canvas id="canvas" width=400 height=400 style="height:500px;width:500px;"></canvas>
<img width=500 height=500 alt="" id="scream" src="canvas.png" style="display:none;" />
<br>
<input type="button" id="rectangle" value="rectangle">
<input type="button" id="selection" value="selection">
&#13;
创建2个按钮,1&gt;选择,2&gt;矩形
选择&gt;删除所有鼠标事件,并将对象的可选状态更改为true,
和矩形&gt;将鼠标事件添加到画布,并将所有对象可选状态更改为false。