jquery 在Fabric js中的选定画布上添加文本

sy5wg1nm  于 2023-08-04  发布在  jQuery
关注(0)|答案(1)|浏览(111)

我有fabric js多个画布,我想在选定的画布上添加文本,而不是数组的最后一项。

如果用户创建多个画布,那么我需要一个选项来添加所选画布上的文本

请运行代码片段或查看当前方法的codepen demo
谢谢你,谢谢

//================== Create Canvas start =================
var createCanvas = document.getElementById("createCanvas");
var canvasInstances = [];
createCanvas.addEventListener('click',function(){
    var canvasContainer = document.getElementById("canvasContainer");
  var newcanvas = document.createElement("canvas");
  //newcanvas.classList.add("active");
  canvasContainer.append(newcanvas);
  var fabricCanvasObj =  new fabric.Canvas(newcanvas, {
    height: 400,
    width: 400,
    backgroundColor: '#ffffff',
  });
  canvasInstances.push(fabricCanvasObj);
  console.log(canvasInstances);
})
//================== Create Canvas End =================

//================== Add Text  ================
var addText = document.getElementById("addText");
addText.addEventListener('click',function(){
    canvasInstances.forEach(function(current,id,array){
    if(id === array.length - 1){
      const converText = new fabric.IText(`Type Text`,{
        type: 'text',
        width: 200,
        fontSize: 20,
        left: 20,
        top: 20,
        fill: '#444'
      });
      
      current.add(converText);
      current.renderAll();
      return false;
    }
  })
})
//================== Add End  =================
*{
  box-sizing: border-box;
}
body{
  background:#ccc;
  display: flex;
  flex-direction: column;
  align-items: center;
 margin-bottom: 200px;
}
.canvas-container{
  margin-bottom:10px;
}
.add-text{
  margin: 20px;
  width: 400px;
  text-align: center;
  border:1px dashed red;
  padding: 15px; 
  cursor:pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.5.0/fabric.min.js"></script>

<div class="add-text" id="addText">Add Text</div> 
<div  id="canvasContainer">
 </div>

<button id="createCanvas">Create Canvas</button>
ahy6op9u

ahy6op9u1#

全局声明canvasobject,可以在下面的代码中尝试

<script type="text/javascript">
var canvasobject;
window.onload = function () {
   canvasobject = new fabric.Canvas('myCanvas');
   canvasobject.backgroundColor = '#0056d6';
   canvasobject.renderAll();
   //
   function addtext() {
       var textvalue = "Type here";
       var fontcolor = "#333";
       var fontFamily = "Baloo 2";
       var myfont = new FontFaceObserver(fontFamily);
       myfont.load()
          .then(function () {
            // when font is loaded, use it.
            var text = new fabric.Text(textvalue, {
              left: 100,
              top: 100,
              fontFamily: fontFamily,
              fill: fontcolor,
            });
            canvasobject.add(text);
            canvasobject.renderAll();
          }).catch(function (e) {
            //console.log(e);
            console.log('font loading failed ' + fontFamily);
       });
   }
}

字符串

相关问题