0
我正在使用fabric js創建形狀的項目。我可以根據fabric js文檔創建所有形狀。拖動現有對象時繪製重複的對象
我有一個問題,在下面創建一個形狀到用戶拖動的形狀。
請在下面找到了更好的理解小提琴,
$(document).ready(function() {
//Getting the canvas
var canvas1 = new fabric.Canvas("canvas2");
var freeDrawing = true;
var divPos = {};
var offset = $("#canvas2").offset();
$(document).mousemove(function(e) {
divPos = {
left: e.pageX - offset.left,
top: e.pageY - offset.top
};
});
$('#2').click(function() {
console.log("Button 2 cilcked");
//Declaring the variables
var isMouseDown = false;
var refRect;
//Setting the mouse events
canvas1.on('mouse:down', function(event) {
//Defining the procedure
isMouseDown = true;
//Getting yhe mouse Co-ordinates
//Creating the rectangle object
if (freeDrawing) {
var rect = new fabric.Rect({
left: divPos.left,
top: divPos.top,
width: 0,
height: 0,
stroke: 'red',
strokeWidth: 3,
fill: ''
});
canvas1.add(rect);
refRect = rect; //**Reference of rectangle object
}
});
canvas1.on('mouse:move', function(event) {
// Defining the procedure
if (!isMouseDown) {
return;
}
//Getting yhe mouse Co-ordinates
if (freeDrawing) {
var posX = divPos.left;
var posY = divPos.top;
refRect.setWidth(Math.abs((posX - refRect.get('left'))));
refRect.setHeight(Math.abs((posY - refRect.get('top'))));
canvas1.renderAll();
}
});
canvas1.on('mouse:up', function() {
//alert("mouse up!");
canvas1.add(refRect);
isMouseDown = false;
canvas1.add();
//freeDrawing=false; // **Disables line drawing
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas2" width=500 height=500 style="height:500px;width:500px;"></canvas>
<img width=500 height=500 alt="" id="scream" src="canvas.png" style="display:none;"/>
<div style="position: relative; width: 1300px; height:30px; border: 2px solid black; margin-top: 5px">
<input type="button" id="2" value="rectangle">
這裏是fiddle
太好了,讓我申請我的項目,謝謝。 –