A. Davis
A. Davis

Reputation: 35

Edit FabricJS objects by HTML <input>

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>

I want to be able to select an object and the input field updates with the color, AND be able to change the color of the object from the input field. I know I can do one way binding with document.getElementById("example").innerHTML and '<input type="color" value="' + canvas.getActiveObject().fill +'">', but what is the best way for two way binding?

Upvotes: 1

Views: 1120

Answers (1)

Durga
Durga

Reputation: 15614

You need to use events object:selected selection:cleared to get the selected object. And set the color picker value from selected object fill value.

DEMO

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>

Upvotes: 1

Related Questions