HTML 5 canvas copy/paste, drag/drop images

Allows copy and pasting or drag and drop of images onto a canvas element. The canvas will grow/shrink to accommodate the image size. Demos how to send base 64 string server-side in a form post.

by rwhal06

HTML

Method 1:<br /> 1. Copy image data into clipboard, or press Print Screen <br /> 2. Press Ctrl+V (page/iframe must be focused): <br /><br /> Method 2:<br /> 1. Drag and drop an image onto the canvas (not sure whether this works)

<div>
  <canvas style="border:1px solid grey;" id="my_canvas" width="200" height="200"></canvas>
  <button id='go' style="display: none;">Get string</button>
  <textarea id="output" style="width: 100%;"></textarea>
</div>

JavaScript

//=====================================================================
//See comment near next big divider line.
let exportsSelf = {};
/**
     * image pasting into canvas
     * 
     * @param {string} canvas_id - canvas id
     * @param {boolean} autoresize - if canvas will be resized
     * @param {function} callback
     */
    exportsSelf.CLIPBOARD_CLASS = function (canvas_id, autoresize, callback) {
        let _self = this;
        let canvas = document.getElementById(canvas_id);
        console.log('CLIPBOARD_CLASS canvas', canvas);
        let ctx = document.getElementById(canvas_id).getContext("2d");
        console.log('CLIPBOARD_CLASS ctx', ctx);

        //handlers
        document.addEventListener('paste', function (e) {
            console.log('paste');
            _self.paste_auto(e);
        }, false);

        /* events fired on the drop targets */
        document.addEventListener("dragover", function (e) {
            // prevent default to allow drop
            e.preventDefault();
        }, false);
        document.addEventListener('drop', function (e) {
            // prevent default action (open as link for some elements)
            // add event handler to canvas if desired instead of document
            //debugger;
            e.preventDefault();
            let items = e.dataTransfer.items;
            for (let i = 0; i < items.length; i++) {
                if (items[i].type.indexOf("image") !== -1) {
                    //document.getElementById("instructions").style.visibility = "hidden";
                    //image
                    let blob = items[i].getAsFile();
                    let URLObj = window.URL || window.webkitURL;
                    let source = URLObj.createObjectURL(blob);
                    _self.paste_createImage(source);
                }
            }
        });

        //on paste
        this.paste_auto = function (e) {
            if (e.clipboardData) {
                let items =...