在以前的fabricjs版本中,我有以下功能可以帮助我在点击鼠标时绘制多边形,并且它已经正确完成。
function draw_polygon(){
//I define the variables that I need
var mode = "add", currentShape;
var newColor = "#FF0000";
var puntos;
var obj;
newColor = this.getRandomColor();
//I prepare the reading of the event mouse: down,
//for when I click, if I am adding the polygon for
//the first time, that is created and added to the canvas
canvas.on("mouse:down", function (event) {
var pos = canvas.getPointer(event.e);
if (mode === "add") {
// console.log(this.getRandomColor);
currentShape = new fabric.Polygon([{
x: pos.x,
y: pos.y
}, {
x: pos.x + 1,
y: pos.y + 1
}], {
fill: "#FF0000",
selectable: false,
olvidar: "olvidar"
});
canvas.add(currentShape);
canvas.renderAll();
newColor= currentShape.get('fill');
mode = "edit";
} else if (mode === "edit" && currentShape && currentShape.type === "polygon") {
//In the case that I have added the polygon, what I have to do is add the points, as I click
var points = currentShape.get("points");
points.push({
x: pos.x ,
y: pos.y
});
puntos = points;
currentShape.set({
points: points
});
canvas.renderAll();
}
});
//I set up a mouse: move listener that modifies the poligo in real time,
//to see where the next point will go, following the position of the mouse
canvas.on("mouse:move", function (event) {
console.log("Hola");
var pos = canvas.getPointer(event.e);
console.log("CurrShape", currentShape);
if (mode == "edit" && currentShape) {
var points = currentShape.get("points");
points[points.length - 1].x = pos.x;
points[points.length - 1].y = pos.y;
currentShape.set({
points: points,
dirty: true
});
currentShape.setCoords();
canvas.renderAll();
}
});
// <%'
// 'Descripción: función que nos ayuda a parar la creación del poligono cuando hacemos doble click
// 'Inputs:
// 'Outputs:
// 'DFDNSCADA0676
// %>
//This function is executed at the end of the creation of the polygon, which is double clicking on the screen
function pararCreacion(){
if (mode === 'edit' || mode === 'add') {
mode = 'normal';
var obj = currentShape.toObject();
currentShape = new fabric.Polygon(puntos,{obj});
currentShape.set({
originY: "top",
originX: "left",
fill: newColor,
type: 'polygon'
});
canvas._objects.pop();
canvas.add(currentShape);
currentShape.set({
selectable: true,
});
$("#Elemento_186").removeAttr("style");
canvas.renderAll();
// <%' Cuando ya termino con el poligono y refresco el canvas entonces es cuando añado el cambio a mi matriz deshacer %>
canvas.off("mouse:move");
}
currentShape = null;
fabric.util.removeListener(fabric.document,'dblclick', pararCreacion); //de esta forma cuando termina la creación me sale de la función y me anula el evento
}
fabric.util.addListener(fabric.document, 'dblclick', pararCreacion);
};
此函数的问题在于它生成一个不可见的矩形或类似的东西,其大小小于画布的大小。或者这就是我在画布上看到的东西,因为这样,我看到那个盒子里面的形状被剪掉了。
我不知道如何更好地解释