Skip to content Skip to sidebar Skip to footer

Opacity Slider For Objects

I'm trying to incorporate an opacity slider so that any selected objects are set to change based on the slider's position (100 being completely visible). I'm using Fabric.js versio

Solution 1:

Assuming you need to update one object at the time then you can you FabriJs function getActiveObject() to update opacity:

var canvas = new fabric.Canvas("c");
canvas.isDrawingMode = true;

// select, draw
$("#select").click(function() {
  canvas.isDrawingMode = false;
});
$("#draw").click(function() {
  canvas.isDrawingMode = true;
});

$("#alpha").slider({
  max: 1,
  min: 0,
  step: 0.1,
  value: 1,
  slide: function(event, ui) {
    if (canvas.getActiveObject()){
        canvas.getActiveObject().setOpacity(ui.value);
        canvas.renderAll();
    }
  },
  stop: function(event, ui) {
    canvas.renderAll();
  }
});

If you will need to play with multiple objects then you'll need to loop and change opacity for each object separately.

Solution 2:

Use object:selected event to get the selected object and on selection:cleared remove active object.

For v2 check.

var canvas = new fabric.Canvas("c");
canvas.isDrawingMode = true;

// select, draw
$("#select").click(function() {
  canvas.isDrawingMode = false;
});
$("#draw").click(function() {
  canvas.isDrawingMode = true;
});

var activeObject = null;

canvas.on('object:selected', function(options) {
  activeObject = options.target;
  $("#alpha").slider("option", "value", activeObject.opacity);
});
canvas.on('selection:cleared', function(options) {
  activeObject = null;
  $("#alpha").slider("option", "value", 1);
});

$("#alpha").slider({
  max: 1,
  min: 0,
  step: 0.1,
  value: 1,
  slide: function(event, ui) {
    activeObject && (activeObject.opacity = ui.value)
    canvas.renderAll();
  },
  stop: function(event, ui) {
    canvas.renderAll();
  }
});
canvas {
  border: solid 1px#000;
}

fieldset {
  max-width: 350px;
}
<linkhref="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" /><scriptsrc="https://code.jquery.com/jquery-3.3.1.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.min.js"></script><canvasid="c"width="400"height="400"></canvas><br><buttonid="draw">Draw</button><buttonid="select">Select</button><br><br><fieldset><legend>Controls</legend><labelfor="alpha">Opactity</label><divid="alpha"name="alpha"></div></fieldset>

Post a Comment for "Opacity Slider For Objects"