Align the text content between the Fabric.js textbox and the text inside a div element

45 Views Asked by At

I want to edit the text content in textbox and render it inside the div element at the same time. But I find the texts in these two places are misaligned, especially in Edge browser. Here is the visual effect result. Misalignment of text content

I tried to set the same text height value for textbox and text div. The result was also the same.

I want to know if there is a way to align the text content in textbox and text div. Thanks for any help!

Here is my code snippet. https://codepen.io/cactusxx/pen/VwRNgLE

var canvas = (this.__canvas = new fabric.Canvas("c"));

var textBox = new fabric.Textbox("", {
  // In order to align the position of the textbox with the text div.
  left: 93,
  top: 93,
  width: 298,
  fontFamily: "Comic Sans",
  fontSize: 30,
  fontWeight: "bold",
  fontStyle: "italic",
  textAlign: "left",
  editable: true,
  hasControls: false,
  editingBorderColor: "green",
  fill: "green",
  objectCaching: false
});

function addTextBox() {
  canvas.add(textBox);
}

function removeTextBox() {
  canvas.remove(textBox);
}

var textContainer = document.getElementById("textContainer");
textContainer.addEventListener("dblclick", (e) => {
  addTextBox();
  textBox.text = document.getElementById("text").textContent;
  canvas.setActiveObject(textBox);
  textBox.enterEditing();
});

// sync text in textbox with text in div element
canvas.on("text:changed", function (e) {
  var textBox = e.target;
  var textContent = textBox.text;
  SyncText(textContent);
});

function SyncText(content) {
  var textElem = document.getElementById("text");
  var newText = document.createTextNode(content);
  textElem.textContent = "";
  textElem.appendChild(newText);
}

textBox.on("editing:exited", function () {
  removeTextBox();
});
#textContainer {
  position: absolute;
  top: 100px;
  left: 100px;
  width: 300px;
  height: 200px;
  border: 1px solid darkgray;
  overflow: hidden;
}

#text {
  font-family: "Comic Sans";
  font-size: 30px;
  color: gray;
  font-style: italic;
  font-weight: bold;
  white-space: pre-wrap;
  border: 1px solid gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.min.js"></script>
<canvas id="c" width="600" height="600" style="border:1px solid #ccc"></canvas>
<div id="textContainer">
  <div id="text">Freedom</div>
</div>

0

There are 0 best solutions below