通过HTML <input />编辑FabricJS对象

时间:2018-07-16 13:06:06

标签: fabricjs

var canvas = new fabric.Canvas('c');
canvas.add(new fabric.Rect({
  left:10,
  top:10,
  width:50,
  height:50,
  fill:'#4169e1'

}));
canvas.add(new fabric.Rect({
  left:140,
  top:140,
  width:50,
  height:50,
  fill:'#800000'

}));
canvas {
 border: black solid 1px;
 padding: 5px;
 margin-top: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.18/fabric.min.js"></script>

<input type='color'></input>
<canvas id="c" width="200" height="200"></canvas>

我希望能够选择一个对象,并且输入字段会用颜色更新,并且能够从输入字段更改对象的颜色。我知道我可以使用document.getElementById("example").innerHTML'<input type="color" value="' + canvas.getActiveObject().fill +'">'进行单向绑定,但是双向绑定的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

您需要使用事件object:selected selection:cleared来获取所选对象。然后从选定的对象填充值中设置颜色选择器值。

演示

var canvas = new fabric.Canvas('c');
canvas.add(new fabric.Rect({
  left: 10,
  top: 10,
  width: 50,
  height: 50,
  fill: '#4169e1'

}));
canvas.add(new fabric.Rect({
  left: 140,
  top: 140,
  width: 50,
  height: 50,
  fill: '#800000'
}));
var colorPick = document.getElementById('colorPick');
var activeSelected;
colorPick.onchange = function() {
  if (activeSelected) {
    activeSelected.fill = this.value;
    activeSelected.dirty = true;
    canvas.renderAll();
  }
};

canvas.on('object:selected', function(option) {
  activeSelected = option.target;
  colorPick.value = activeSelected.fill;
})

canvas.on('selection:cleared', function(option) {
  activeSelected = null;
  console.log(activeSelected)
});
canvas {
 border: black solid 1px;
 padding: 5px;
 margin-top: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.18/fabric.min.js"></script>

<input type='color' id='colorPick'></input>
<canvas id="c" width="200" height="200"></canvas>