copy and paste on canvas

copy and paste on canvas

by vijayweb

HTML

<div id="box">
<canvas style="" id="my_canvas1"></canvas>
<canvas style="" id="my_canvas2"></canvas>
<canvas style="" id="my_canvas3"></canvas>
<canvas style="" id="my_canvas4"></canvas>

</div>
<button id="add_canvas">
Add a new Canvas
</button>

CSS

canvas {
  width:640px;
  border:1px solid grey;
}

JavaScript

$("#add_canvas").click(function() {
	var idval = "my_canvas" + Math.round(Math.random() * 100) + 1;
	var newCanvas = $('<canvas/>', {
		id: idval
	});
       $("#box").append(newCanvas);

});

$('#box').on('click','canvas', function() {
var id = $(this).attr('id');
CLIPBOARD(id, true);
});




/**
 * image pasting into canvas
 * 
 * @param {string} canvas_id - canvas id
 * @param {boolean} autoresize - if canvas will be resized
 */
function CLIPBOARD(canvas_id, autoresize) {

	var _self = this;
	var canvas = document.getElementById(canvas_id);
	var ctx = document.getElementById(canvas_id).getContext("2d");
	var ctrl_pressed = false;
	var command_pressed = false;
	var paste_event_support;
	var pasteCatcher;

	//handlers
	document.addEventListener('keydown', function (e) {
		_self.on_keyboard_action(e);
	}, false); //firefox fix
	document.addEventListener('keyup', function (e) {
		_self.on_keyboardup_action(e);
	}, false); //firefox fix
	document.addEventListener('paste', function (e) {
		_self.paste_auto(e);
	}, false); //official paste handler

	//constructor - we ignore security checks here
	this.init = function () {
		pasteCatcher = document.createElement("div");
		pasteCatcher.setAttribute("id", "paste_ff");
		pasteCatcher.setAttribute("contenteditable", "");
		pasteCatcher.style.cssText = 'opacity:0;position:fixed;top:0px;left:0px;width:10px;margin-left:-20px;';
		document.body.appendChild(pasteCatcher);

		// create an observer instance
		var observer = new MutationObserver(function(mutations) {
			mutations.forEach(function(mutation) {
				if (paste_event_support === true || ctrl_pressed == false || mutation.type != 'childList'){
					//we already got data in paste_auto()
					return true;
				}

				//if paste handle failed - capture pasted object manually
				if(mutation.addedNodes.length == 1) {
					if (mutation.addedNodes[0].src != undefined) {
						//image
						_self.paste_createImage(mutation.addedNodes[0].src);
					}
					//register cleanup after...