Add delete icon on image in HTML5 and Fabric js canvas

I am using HTML5 and Fabric.js. I upload several images. But I want the user to be able to delete the uploaded image. I will show you one screenshot.enter image description here

I want to add a single delete icon to the image when the user clicked on the image.

HTML code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>

<input type="file" id="file">
<input type="color" value="blue" id="fill" />
<select id="font">

Java Sript Code:

var canvas = new fabric.Canvas('canvas');

document.getElementById('file').addEventListener("change", function (e) {
  var file = e.target.files[0];
  var reader = new FileReader();
  console.log("reader   " + reader);
  reader.onload = function (f) {
    var data = f.target.result;
    fabric.Image.fromURL(data, function (img) {
      var oImg = img.set({left: 70, top: 100, width: 250, height: 200, angle: 0}).scale(0.9);
      canvas.add(oImg).renderAll();
      canvas.setActiveObject(oImg);
      // add an event listener
      oImg.on('mousedown', function(){
        // bring the image to front
        oImg.bringToFront();
        });
    });
  };
  reader.readAsDataURL(file);
});

$('#fill').change(function(){
  var obj = canvas.getActiveObject();
  if(obj){
    obj.setFill($(this).val());
  }
  canvas.renderAll();
});

$('#font').change(function(){
  var obj = canvas.getActiveObject();
  if(obj){
    obj.setFontFamily($(this).val());
  }
  canvas.renderAll();
});

function addText() {
  var oText = new fabric.IText('Tap and Type', { 
    left: 100, 
    top: 100 ,
  });

  canvas.add(oText);
  canvas.setActiveObject(oText);
  $('#fill, #font').trigger('change');
  oText.bringToFront();
}

document.querySelector('#txt').onclick = function (e) {
  e.preventDefault();
  canvas.deactivateAll().renderAll();
  document.querySelector('#preview').src = canvas.toDataURL();
};

Css Code:

canvas{
  border: 1px solid black;
}

You can see this link. Write custom text on an image canvas using fabric.js and HTML5

After clicking on the cross icon, delete it. You can add a delete icon. If so, give me an idea about this.

+4
source share
1 answer

, , , . su, . , , . - , , .

-

<button id="remove" style="display:none">remove</button>

$('#remove').on('click', function(){
  canvas.getActiveObject().remove();
});

canvas.on('object:selected', function(o) {
  if (o.target.isType('image')) {
    $('#remove').show();
  }
});

canvas.on('selection:cleared', function() {
    $('#remove').hide();
});
+2

Source: https://habr.com/ru/post/1624561/


All Articles