添加特定类型的对象时如何更改“模式”?

问题描述 投票:1回答:1

我正在使用fabricjs 1.7.20并具有“选择”和“绘制”模式。如何在我添加文本时(使用按钮,同时仍处于绘图模式)将其设置为选择模式以便我可以立即编辑文本对象?

var canvas = new fabric.Canvas("c", {
  backgroundColor: "#fff"
});
canvas.setHeight(300);
canvas.setWidth(300);

// Add text
function Addtext() {
  var text = new fabric.IText("Tap & type", {
    fontSize: 30,
    top: 10,
    left: 10,
    width: 200,
    height: 200,
    textAlign: "center"
  });
  canvas.add(text);
  canvas.setActiveObject(text);
}

// Modes
$("#select").click(function() {
  canvas.isDrawingMode = false;
});
$("#draw").click(function() {
  canvas.isDrawingMode = true;
});
canvas {
  border: 1px solid #dddddd;
  margin-top: 10px;
  border-radius: 3px;
}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.min.js"></script>
<button onclick="Addtext()">Add Text</button>
<button id="draw">Draw Mode</button>


<canvas id="c"></canvas>
javascript fabricjs
1个回答
1
投票

你可以使用文本方法中的enterEditing(),如果需要也可以使用selectAll()。

var canvas = new fabric.Canvas("c", {
  backgroundColor: "#fff"
});
canvas.setHeight(300);
canvas.setWidth(300);

// Add text
function Addtext() {
  var text = new fabric.IText("Tap & type", {
    fontSize: 30,
    top: 10,
    left: 10,
    width: 200,
    height: 200,
    textAlign: "center"
  });
  canvas.add(text);
  canvas.setActiveObject(text);
  text.enterEditing();
  text.selectAll();
  text.renderCursorOrSelection();  // or canvas.renderAll();
  canvas.isDrawingMode = false;
}

// Modes
$("#select").click(function() {
  canvas.isDrawingMode = false;
});
$("#draw").click(function() {
  canvas.isDrawingMode = true;
});
canvas {
  border: 1px solid #dddddd;
  margin-top: 10px;
  border-radius: 3px;
}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.min.js"></script>
<button onclick="Addtext()">Add Text</button>
<button id="draw">Draw Mode</button>


<canvas id="c"></canvas>
© www.soinside.com 2019 - 2024. All rights reserved.