Home » CSS3, Design, HTML5, Javascript

HTML5 Image crop tool without server side using javascript

18 October 2012 No Comment
Share on Facebook

We have seen image crop tool using server side script, below is HTML5 image crop tool to edit image on browser using HTML5 Canvas. So highlight of this script is, it just uses only HTML5 and js to crop and display the cropped image on Canvas.

No upload script is need to edit the original file, so no server overload.This cropping tool using HTML5 does not require any server-side script to crop. Just click and drag over the image to make selection and then press “crop Image” button to replicate crop on your browser.

Cropped image is updated on another Canvas.

Note: Crop tool works well in Chrome browser.

Before going into the code section go through the article on

 



 

HTML5 Image Crop Tool using Javascript:

Below is the entire code for creating html5 canvas image crop tool with drag and crop support. The selection on the image also shows marching ants effect similar to what appears on the famous image editing tools like Photoshop.

<!doctype HTML>
<html>
<head>
<title>Marching ants | marquee tool in HTML5</title>

<style id="basics">
	/* Basic standard module */
	.mod {
		margin:.6em auto;
		padding:2px;
	}
	.mod .bd {
		cursor:pointer;
		text-align:center;
		height:99%;
	}
</style>
<style>
	#testTop{
		background-color:#666666;
	}

	.marchingants2 {
		background:url(images/ants.gif) repeat-y -6px -4px;

		padding:0 2px;
		position:relative;
	}
	.marchingants2 .inner {
		background:url(images/ants.gif) repeat-x 0 -6px;
		padding:2px 0 0 0;
		height:100%;
	}
	.marchingants2 .hd {
		background:url(images/ants.gif) repeat-y 0 0;
		height:100%;
		margin-bottom:4px;
		position:absolute;
		right:0;
		width:2px;
	}
	.marchingants2 .ft {
		background:url(images/ants.gif) repeat-x 0 0;
		height:2px;
	}

	.marchingants2,
	.marchingants2 .inner,
	.marchingants2 .hd,
	.marchingants2 .ft {
		-webkit-animation-duration: 0.3s;
		-webkit-animation-iteration-count: infinite;
		-webkit-animation-timing-function: linear;
	}
	.marchingants2 {
		-webkit-animation-name: march-up;
	}
	.marchingants2 .inner {
		-webkit-animation-name: march-right;
	}
	.marchingants2 .hd {
		-webkit-animation-name: march-down;
	}
	.marchingants2 .ft {
		-webkit-animation-name: march-left;
	}

	@-webkit-keyframes march-right {
		from {
			background-position-x: 0;
		}
		to {
			background-position-x: 8px;
		}
	}
	@-webkit-keyframes march-left {
		from {
			background-position-x: 8px;
		}
		to {
			background-position-x: 0;
		}
	}
	@-webkit-keyframes march-up {
		from {
			background-position-y: 8px;
		}
		to {
			background-position-y: 0;
		}
	}
	@-webkit-keyframes march-down {
		from {
			background-position-y: 0;
		}
		to {
			background-position-y: 8px;
		}
	}
</style>

</head>
<body onLoad="init()">

<canvas id="canvas1" width="400" height="408" style="border: 1px solid black; background:url(guardians.jpg)">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>

<input type="button" id="cropBTN" value="Crop Image">

<canvas id="canvasDestination" width="400" height="408" style="border: 1px solid black;">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>

<img src="guardians.jpg" id="srcIMG" width="0" height="0" />

<div style="position: absolute;top: 10px; left: 10px; width: 0px; height: 0px; z-index: 5;" class="mod marchingants2" id="testAnt">
	<div class="inner">
		<div class="hd"></div>
		<div class="bd"></div>
		<div class="ft"></div>
	</div>
</div>

<div style="font-family: Verdana; font-size: 12px;">
  <p>Drag Over the Image and Press "Crop Image"</p>
  <p><a href="http://simonsarris.com/blog/510-making-and-moving-selectable-shapes-on-an-html5-canvas-updated">link to tutorial</a></p>
  <p>By <a href="http://www.designscripting.com">designscripting.com</a></p>
</div>

<script type="text/javascript">
function CanvasState(canvas)
{
	this.canvas = canvas;
 	this.width = canvas.width;
  	this.height = canvas.height;
  	this.ctx = canvas.getContext('2d');

	var srcImageObj = document.getElementById('srcIMG')
	var canvasDest = document.getElementById("canvasDestination");
	var contextDest = canvasDest.getContext("2d");

	var cropButton = document.getElementById('cropBTN')

	cropButton.addEventListener('click', function(e) {

		var ant = document.getElementById('testAnt');
		var left = ant.style.left;
		var top =	ant.style.top;
		var Width = ant.style.width;
		var Height = ant.style.height;

		var sourceX = left.substring(0,left.length-2)-5;
		var sourceY = top.substring(0,top.length-2);
		var sourceWidth = Width.substring(0,Width.length-2);
		var sourceHeight = Height.substring(0,Height.length-2);
		var destWidth = sourceWidth;
		var destHeight = sourceHeight;
		var destX = canvasDest.width / 2 - destWidth / 2;
		var destY = canvasDest.height / 2 - destHeight / 2;
		//Clear before draw
		contextDest.clearRect(0, 0, canvasDest.width, canvasDest.height);
		//Drawing the cropped Image
		contextDest.drawImage(srcImageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
	});

	// This complicates things a little but but fixes mouse co-ordinate problems
	// when there's a border or padding. See getMouse for more detail
	var stylePaddingLeft, stylePaddingTop, styleBorderLeft, styleBorderTop;
	if (document.defaultView && document.defaultView.getComputedStyle)
	{
		this.stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingLeft'], 10)      || 0;
		this.stylePaddingTop  = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingTop'], 10)       || 0;
		this.styleBorderLeft  = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderLeftWidth'], 10)  || 0;
		this.styleBorderTop   = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderTopWidth'], 10)   || 0;
	}
	// Some pages have fixed-position bars (like the stumbleupon bar) at the top or left of the page
	// They will mess up mouse coordinates and this fixes that
	var html = document.body.parentNode;
	this.htmlTop = html.offsetTop;
	this.htmlLeft = html.offsetLeft;

	this.dragging = false;
	this.mx = 0;
	this.my = 0;
	// This is an example of a closure!
	// Right here "this" means the CanvasState. But we are making events on the Canvas itself,
	// and when the events are fired on the canvas the variable "this" is going to mean the canvas!
	// Since we still want to use this particular CanvasState in the events we have to save a reference to it.
	// This is our reference!
	var myState = this;
	//fixes a problem where double clicking causes text to get selected on the canvas
	canvas.addEventListener('selectstart', function(e) { e.preventDefault(); return false; }, false);
	// Up, down, and move are for dragging
	canvas.addEventListener('mousedown', function(e) {
	var mouse = myState.getMouse(e);
		this.mx = mouse.x;
		this.my = mouse.y;

	var ant = document.getElementById('testAnt');
		ant.style.left = (this.mx+10)+"px";
		ant.style.top = (this.my)+"px";
		ant.style.width = (0)+"px";
		ant.style.height = (0)+"px";

	 	myState.dragging = true;

  }, true);

  canvas.addEventListener('mousemove', function(e) {

    if (myState.dragging)
	{

      var mouse = myState.getMouse(e);
	 	  myState.clear(e);

	  var width =  mouse.x - this.mx;
	  var height =  mouse.y - this.my;

	  var ant = document.getElementById('testAnt');
		  ant.style.left = (this.mx+10)+"px";
		  ant.style.top = (this.my)+"px";
		  ant.style.width = (width-6)+"px";
		  ant.style.height = (height-6)+"px";
    }
  }, true);
  canvas.addEventListener('mouseup', function(e) {
  		  myState.dragging = false;
  }, true);
  // double click for making new shapes
  canvas.addEventListener('dblclick', function(e) {
 		  myState.clear(e);
  }, true);
}

CanvasState.prototype.clear = function() {
  		 this.ctx.clearRect(0, 0, this.width, this.height);
}

CanvasState.prototype.getCanvasHandle = function(e) {
		return this.ctx;
}

// Creates an object with x and y defined, set to the mouse position relative to the state's canvas
// If you wanna be super-correct this can be tricky, we have to worry about padding and borders
CanvasState.prototype.getMouse = function(e) {
	var element = this.canvas, offsetX = 0, offsetY = 0, mx, my;

	// Compute the total offset
	if (element.offsetParent !== undefined) {
		do {
		  offsetX += element.offsetLeft;
		  offsetY += element.offsetTop;
		} while ((element = element.offsetParent));
	}

	// Add padding and border style widths to offset
	// Also add the <html> offsets in case there's a position:fixed bar
	offsetX += this.stylePaddingLeft + this.styleBorderLeft + this.htmlLeft;
	offsetY += this.stylePaddingTop + this.styleBorderTop + this.htmlTop;

	mx = e.pageX - offsetX;
	my = e.pageY - offsetY;
	// We return a simple javascript object (a hash) with x and y defined
	return {x: mx, y: my};
}

function init() {
	 var myCanvas = new CanvasState(document.getElementById('canvas1'));
}
</script>

</body>
</html>

Conclusion: In this tutorial we have seen how to create simple crop tool in html5 and javascript. Please share your comments.

GET THE UPDATES VIA EMAIL

We don't share your email anywhere, grab our rss via feedburner