Skip to content Skip to sidebar Skip to footer

How To Do Copy And Paste The Image From User System To Canvas Using Fabric.js

Can we do copy(Ctrl+C) and paste(Ctrl+V) the image from User system(desktop/any folder) to canvas using fabric.js. I have seen the copy and paste program inside the canvas, I have

Solution 1:

If you're targeting modern browsers you can combine 2 new (but widely adopted) html5 features to accomplish your task:

  1. You can create a dropzone on your page using the dragover and drop events.

  2. Then you can use the FileReader API to read the image files into an image object.

  3. Then it's back to FabricJS to load the image as usual.

Here's a tutorial describing how to do the hard bits (#1,#2): http://www.html5rocks.com/en/tutorials/file/dndfiles/

[ Added code that SOMETIMES allows cut/paste of image files ]

Most modern browsers support binding the “paste” event.

// listen for the paste eventwindow.addEventListener("paste",pasteImage);

But...!!

Support for non-text mime types (ie “image”) is scarce. Chrome seems to support it “off-and-on”.

…And browsers are constantly revising their cut/paste capabilities because of security concerns.

Here is code that sometimes works in Chrome.

// listen for the paste event
window.addEventListener("paste",pasteImage);

functionpasteImage(event) {

    // get the raw clipboardDatavar cbData=event.clipboardData;

    for(var i=0;i<cbData.items.length;i++){

        // get the clipboard itemvar cbDataItem = cbData.items[i];
        var type = cbDataItem.type;

        // warning: most browsers don't support image data typeif (type.indexOf("image")!=-1) {
            // grab the imageData (as a blob)var imageData = cbDataItem.getAsFile();
            // format the imageData into a URLvar imageURL=window.webkitURL.createObjectURL(imageData);
            // We've got an imageURL, add code to use it as needed// the imageURL can be used as src for an Image object
        }
    }
}

Post a Comment for "How To Do Copy And Paste The Image From User System To Canvas Using Fabric.js"