简体   繁体   中英

remove image from canvas - fabricjs (javascript)

I'm working on web application most of the part has been covered by angular js. I am stuck at a point. I used fabric.js to manipulate images on canvas and it is the best way of doing this. Everything is working fine but I can not add a close button on uploaded image like shown in image.

在此输入图像描述

This angular image comes upon a canvas tag. Fabric.js gives me ability to rotate and add images but how could I close this particular image. So far I've done with the code is :

var canvas = window._canvas = new fabric.Canvas('c');

    var imgElement = document.getElementById('my-image');
    var imgInstance = new fabric.Image(imgElement);
    canvas.add(imgInstance);

My canvas element:

<canvas height="282" width="181" id="c" class="lower-canvas"></canvas>

My uploaded image element.

<img style="display: none;" src="http://*******/angular.png" class="topimg canvas-img" id="my-image">

Below is what I am getting from fabric.js

在此输入图像描述

My question is, how could I close or remove this uploaded image on canvas ? Is there any another way to doing this instead of fabric.js ? If it is, please share.. I do not want to clear canvas element from common button. I need to remove image one by one.

Try this

$('#remove').click(function(){
    var object = canvas.getActiveObject();
    if (!object){
        alert('Please select the element to remove');
        return '';
    }
    canvas.remove(object);
});

Fiddle for remove object on button click

Fiddle with custom remove button on object

You can delete the selected object from the canvas when the user pressed DELETE with this code:

window.onkeydown = onKeyDownHandler;

function onKeyDownHandler(e) {
   switch (e.keyCode) {
      case 46: // delete
         var activeObject = canvas.getActiveObject();
         if (!activeObject) canvas.remove(activeObject);
   }
   e.preventDefault(); 
};

You can manipulate the controls from FabricJS, but it takes some effort. Checkout this question: Adding Custom Delete (Back,toFront) Button to Controls and this Fiddle: http://jsfiddle.net/86bTc/8/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM