0


请帮我解决这个问题。
1. 我在位置有一个文本显示:left: 10, top: 10.
2. 使用 viewportTransform 将 viewPort 移动到新位置:通过 X 轴 100 和 Y 轴 100 平移
3. 文本对象正在移动到

预期的新位置:
用户可以通过单击文本(在新位置)来选择文本对象('hello world')

实际:
第一次,用户不能点击文本对象。& 对象边界仍然在旧位置(左:10,上:10)。(见附图)
请检查我的演示代码。
我正在使用 Fabricjs 版本 2.4.0 这个演示

如何通过这个问题?
谢谢 !

错误的光标位置

var canvasObject = document.getElementById("editorCanvas");
  // set canvas equal size with div
  $(canvasObject).width($("#canvasContainer").width());
  $(canvasObject).height($("#canvasContainer").height());
 
 canvas = new fabric.Canvas('editorCanvas', {
    backgroundColor: 'white',
    selectionLineWidth: 2,
    width: $("#canvasContainer").width(),
    height: $("#canvasContainer").height()
  });

  canvas.controlsAboveOverlay = true;

  // Add a text to canvas
  var text = new fabric.Text('hello world', { left: 10, top: 10 });
  canvas.add(text);
  
  // Transform View
  canvas.viewportTransform[4] = 100;
  canvas.viewportTransform[5] = 100;
  canvas.requestRenderAll();
#canvasContainer {
            width: 100%;
            height: 100vh;
            background-color: gray;
        }
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.0/fabric.js"></script>


<div id="canvasContainer">
  <canvas id="editorCanvas"></canvas>
</div>

4

2 回答 2

2

调用object.setCoords(),它将在更改后设置边界坐标。并检查When-to-call-setCoords

演示

var canvasObject = document.getElementById("editorCanvas");
// set canvas equal size with div
$(canvasObject).width($("#canvasContainer").width());
$(canvasObject).height($("#canvasContainer").height());

canvas = new fabric.Canvas('editorCanvas', {
  backgroundColor: 'white',
  selectionLineWidth: 2,
  width: $("#canvasContainer").width(),
  height: $("#canvasContainer").height()
});

canvas.controlsAboveOverlay = true;

// Add a text to canvas
var text = new fabric.Text('hello world', {
  left: 10,
  top: 10
});
canvas.add(text);

// Transform View
canvas.viewportTransform[4] = 100;
canvas.viewportTransform[5] = 100;
setObjectCoords();
canvas.requestRenderAll();

function setObjectCoords(){
  canvas.forEachObject(function(object){
    object.setCoords();
  })
}
#canvasContainer {
  width: 100%;
  height: 100vh;
  background-color: gray;
}
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.0/fabric.js"></script>


<div id="canvasContainer">
  <canvas id="editorCanvas"></canvas>
</div>

于 2018-10-06T08:49:10.943 回答
0

不确定这是否仍然是一个问题,但您可以执行以下操作:

let vpt = [...canvas.viewportTransform];
vpt[4] = 100;
vpt[5] = 100;
canvas.setViewportTransform(vpt);

有同样的问题,并解决了它。

于 2021-09-02T08:08:09.580 回答