Designscripting Actionscript, Flex, Flash slideshow, Slideshow, Html5, Flash tutorials, advance flash, 3d Flash, ActionScript Tutorials, CSS, Flash video tutorials,Effects. Mon, 08 Jul 2013 07:50:28 +0000 en-US hourly 1 To fetch the latest youtube video from user channel using php Mon, 22 Apr 2013 09:53:52 +0000 Related posts:
  1. Top 7 HTML5 Video Player | Free HTML5 player
  2. Introduction to Flex or Flex Basic Video Tutorial
  3. Play Flv enables Windows Media Player open FLV files
  4. Full-screen mode in Flash Player without user interaction
  5. Learn Flex 4 in a week – Flex Video Training

If you need to create a widget & showcase the latest video uploaded in youtube channel to your users. Can be in your website or advertisements or anywhere, it is now possible with youtube API.


Youtube feeds

The API returns a videos feed in response to a request to search for videos. A videos feed contains a maximum of 999 entries. To retrieve search results, send an API request to the following URL:

Videos uploaded by a specific user

To request a feed of all videos uploaded by the currently logged-in user, send a GET request to the following URL. This request requires an authentication token, which enables YouTube to identify the user.

Learn more:

Using PHP to fetch latest youtube channel video:

We are going to use php code to fetch latest youtube user channel video of “officialpsy”

PHP code to fetch youtube channel:

$feedURL = '';
$sxml = simplexml_load_file($feedURL);
	foreach ($sxml->entry as $entry) {
      $media = $entry->children('media', true);
      $watch = (string)$media->group->player->attributes()->url;
      $thumbnail = (string)$media->group->thumbnail[0]->attributes()->url;
      $videoURL = str_replace("&feature=youtube_gdata_player","?feature=player_detailpage",$watch);
	  $videoURL = str_replace("watch?v=","embed/",$videoURL);
      <div class="videoitem">
        <div class="videothumb">
        	<iframe width="470" height="360" src="<?php echo $videoURL; ?>" frameborder="0" allowfullscreen></iframe>
        <div class="videotitle">
            <h3><a href="<?php echo $watch; ?>" class="watchvideo"><?php echo $media->group->title; ?></a></h3>
            <p><?php echo $media->group->description; ?></p>
<?php } ?>


In this sample snippet code we have seen how to get the lastest youtube video from user channel.

]]> 0
Mobile & Tablet emulator online to test responsive design Wed, 10 Apr 2013 08:05:27 +0000 Related posts:
  1. Tips: In Responsive Design how to remove content using css media queries
  2. Aakash Tablet and Ubislate-7 Tablet review buy
  3. Android Design – Ice Cream Sandwich
  4. Best mobile sites
  5. Best Mobile websites optimized for iPhone

Mobile & Tablet Emulator is an useful online tool to check the screen resolution on different mobile and tablet devices.
Do you check your mobile website screen resolution on multiple devices straight from your desktop. It is now possible with this mobile emulator.

Launch >> Mobile & Tablet Emulator

Below web app screenshot and some the devices in which you can check your screen resolution.

Mobile Emulator Web app screenshots:


mobile-emulator 1




mobile-emulator 3

Mobile devices supported:

  • BlackBerry: 320×240
  • iphone4s: 320×480
  • iphone5: 320×568
  • Galaxy S3: 360×640
  • Lumia 900: 480×800

Tablet devices supported:

  • Kindle Fire 7: 533×853
  • Google Nexus: 603×966
  • Apple iPad: 768×1024

Download directly from Google webstore. Best way to check screen responsive design for mobile devices & tablet online.

]]> 0
Simple HTML5 CSS3 Keyframe Animation Sun, 03 Mar 2013 07:46:45 +0000 Related posts:
  1. CSS3 Generator
  2. creating marching ants html5 and javascript
  3. Simple calculator code using html javascript css3
  4. CSS3 Multi-column layout | CSS
  5. HTML5 Image crop tool without server side using javascript

Now we can create eye catching animation using CSS3 and HTML5, so to describe that feature. We have explained how to create ticking or rotating clock hand in middle of the circle using CSS3 animation.

In this simple article on creating CSS3 animation we have used two important CSS3 properties.

  • animation
  • @keyframes

Note that we have to add prefix of -webkit-, -moz-, -ms-, -o-, infront of animation and keyframes to work on respective browsers.


Simple HTML5 CSS3 Animation code:

Below is the sample code which creates the ticking hand animation over circular background. Code explanation is below.

<!doctype html>
<meta charset="utf-8">
<title>Simple CSS3 Animation</title>
	-webkit-animation:colorChange 5s linear .5s infinite;
	-webkit-transform-origin:0% 50%;
	-moz-animation:colorChange 5s linear .5s infinite;
	-moz-transform-origin:0% 50%;
	-o-animation:colorChange 5s linear .5s infinite;
	-o-transform-origin:0% 50%;
@-webkit-keyframes colorChange
	0%   {background: red; -webkit-transform: rotate( 0deg );}
	50%  {background: blue;  -webkit-transform: rotate( 180deg );}
	100% {background: red; -webkit-transform: rotate( 360deg );}

@-moz-keyframes colorChange
	0%   {background: red; -moz-transform: rotate( 0deg );}
	50%  {background: blue;  -moz-transform: rotate( 180deg );}
	100% {background: red; -moz-transform: rotate( 360deg );}

@-o-keyframes colorChange
	0%   {background: red; -o-transform: rotate( 0deg );}
	50%  {background: blue;  -o-transform: rotate( 180deg );}
	100% {background: red; -o-transform: rotate( 360deg );}		


<div id="circle"></div>
<div id="rectBox"></div>


HTML5 & CSS3 Animation code explanation:

The core concept behind this css3 animation is with the help of two new css3 properties as said earlier in the article.

css3 animation property:

To animate any style with css3 animation property. We have to configure the timing and duration of the animation, also how the animation sequence should progress over time as keyframes.

Some of the css3 animation sub properties are

Specifies the name of the @keyframes at-rule describing the animation’s keyframes.

Configures the length of time that an animation should take to complete one cycle.

Configures the timing of the animation; that is, how the animation transitions through keyframes.

Configures the delay between the time the element is loaded and the beginning of the animation sequence.

Configures the number of times the animation should repeat; you can specify infinite to repeat the animation indefinitely.


animation:colorChange 5s linear .5s infinite;

css3 animation sequence using keyframes:

Keyframe describes how the animated element should render at a given time during the animation sequence.

We can define keyframes of the animation in either

  • Percentage
  • From to

In the example we have used percentage method to define keyframes

@-webkit-keyframes colorChange
	0%   {background: red; -webkit-transform: rotate( 0deg );}
	50%  {background: blue;  -webkit-transform: rotate( 180deg );}
	100% {background: red; -webkit-transform: rotate( 360deg );}

So this is a simple method to create css3 animation properties using html5, If you have any suggestion or doubt comment below.

keywords to here:

  • css animations
  • css3 animation property
  • css3 keyframe
  • css keyframe animation
]]> 0
Simple calculator code using html javascript css3 Sun, 24 Feb 2013 14:54:31 +0000 Related posts:
  1. Back button javascript | html go back history
  2. javascript to print HTML page
  3. HTML5 Image crop tool without server side using javascript
  4. div background image | using CSS Javascript
  5. creating marching ants html5 and javascript

Simple javascript and html coded calculator does simple operations like Addition, Subtraction, division and multiplication.

The code is free to use or modify.

I am distributing to code to be useful for beginners.


Simple Calculator (html, css, javascript)

<!doctype html>
<meta charset="utf-8">
<title>Untitled Document</title>
	border:1px solid #666;
	padding:10px 0px;
	margin:4px 0px 0px 4px;
	margin:20px 0px 0px 4px;

	font-family: Arial, Helvetica, sans-serif;
	font-size: 14px;
	color: #000;
	background: -moz-linear-gradient(
		#f5c7d7 0%,
	background: -webkit-gradient(
		linear, left top, left bottom, 
	-moz-border-radius: 10px;
	-webkit-border-radius: 10px;
	border-radius: 10px;
	border: 1px solid #ff5c5c;
		0px 1px 3px rgba(000,000,000,0.5),
		inset 0px 0px 2px rgba(255,255,255,1);
		0px 1px 3px rgba(000,000,000,0.5),
		inset 0px 0px 2px rgba(255,255,255,1);
		0px 1px 3px rgba(000,000,000,0.5),
		inset 0px 0px 2px rgba(255,255,255,1);
		0px -1px 0px rgba(000,000,000,0.4),
		0px 1px 0px rgba(255,255,255,0.3);


var control = "";
var temp = "";
function controlPressedfn(val){

	temp = document.getElementById("screenTXT").value;
	document.getElementById("indic").innerHTML = temp+" "+val;
	control = val;

function keyPressedfn(val){

function resultfn(){
	var byNum = document.getElementById("screenTXT").value;
	var result=""
		case '+':
			result = parseInt(temp)+parseInt(byNum);
		case '-':
			result = parseInt(temp)-parseInt(byNum);
		case 'x':
			result = parseInt(temp)*parseInt(byNum);
		case '%':
			result = parseInt(temp)/parseInt(byNum);
	document.getElementById("indic").innerHTML = "";
	document.getElementById("screenTXT").value = result;


function clearfn(){
	document.getElementById("screenTXT").value ="0";
	document.getElementById("indic").innerHTML = "";

<body><div id="wrapper">
	<div id="container">
    	<div id="indic" class="indic"></div>
    	<input id="screenTXT" type="text" size="28" class="inputClass" value="" disabled >
        <div style="float:right;margin-right:3px;"><button class="numericBTN controlBTN" onClick="clearfn();">C</button></div><div style="clear:both"></div>
        <button class="numericBTN" onClick="keyPressedfn(7)">7</button>
        <button class="numericBTN" onClick="keyPressedfn(8)">8</button>
        <button class="numericBTN" onClick="keyPressedfn(9)">9</button>
        <button class="numericBTN controlBTN" onClick="controlPressedfn('+')">+</button>
		<button class="numericBTN" onClick="keyPressedfn(4)">4</button>
        <button class="numericBTN" onClick="keyPressedfn(5)">5</button>
        <button class="numericBTN" onClick="keyPressedfn(6)">6</button>
        <button class="numericBTN controlBTN" onClick="controlPressedfn('-')">-</button>
        <button class="numericBTN" onClick="keyPressedfn(1)">1</button>
        <button class="numericBTN" onClick="keyPressedfn(2)">2</button>
        <button class="numericBTN" onClick="keyPressedfn(3)">3</button>
        <button class="numericBTN controlBTN" onClick="controlPressedfn('x')">x</button>
        <button class="numericBTN" onClick="keyPressedfn('.')">.</button>
        <button class="numericBTN" onClick="keyPressedfn(0)">0</button>
        <button class="numericBTN" onClick="resultfn()">=</button>
        <button class="numericBTN controlBTN" onClick="controlPressedfn('%')">%</button>                

Simple calculator script to use in your project for free. created using html css javascript.

]]> 0
iPhone websites | Top mobile websites 2013 Mon, 28 Jan 2013 12:19:13 +0000 Related posts:
  1. Best Mobile websites optimized for iPhone
  2. Best mobile sites
  4. My First Mobile Jquery site | Getting started with Mobile Jquery
  5. Mobile jQuery page creation basics | Mobile page structure in Mobile jQuery

Top mobile websites designed for iPhone can be created using HTML, CSS, javascript combinations or with the help of media queries to load different style according to the device width will also supports in iphone.

We can either use media queries to create mobile websites or design different domain mobile website and redirect to subdomain.

iPhone Websites

Here we have showcased some of top mobile websites 2013 created for iphone or any mobile browser. So the idea of showcasing the iphone websites is for referencing before we create our mobile website.

article source: mobile websites

Jaguar Cars


The official home of Jaguar USA Mobile Website. Jaguar luxury cars feature innovative designs along with legendary performance to deliver one of the top sports cars in the industry.

Al Fresco All Natural


l fresco all natural offers fully cooked or fresh, gourmet, all natural, gluten free chicken sausages, all natural recipes and meal ideas. Al fresco all natural mobile website contains details for consumer interaction, store locators, online store, contact them and company history to help you live your life with flavor.

Copper Cottage


Plumbing, heating, or air conditioning, Copper Cottage keeps it running smoothly in Sioux Falls and Rapid City, SD and Sioux City and Spencer, IA.



Pedigree strives to provide really good dog food for your dog. That means healthy and nutritious dog food that also tastes really good to your dog.



Kelloggs – From cereals to snacks and recipes for every ocassion Official Website has everything you need including coupons.



Breitling is a luxury brand of Swiss watches produced by Breitling SA, a private company headquartered in Grenchen.
A unique and uncompromising philosophy dedicated to serving professionals since 1884. Breitling is a Developer and manufacturer of technically-oriented watches, mostly mechanical and electronic chronometers.



GMC vehicles have the power needed to get the job done. Choose from GMCs lineup of pickup trucks, diesel trucks, SUVs, crossovers, vans and commercial vehicles using this mobile website.

Sea World


Sea World Whale Watching Gold Coast – Sea World Whale Watch offer exciting close encounters with Humpback Whales on Australia Gold Coast. Australia premier whale watching experience.



Shop for Affordable Home Decor & Stylish Chic Furniture at Z Gallerie. Browse Our Unique Collection of Furniture, Art, Lamps, Sofas, Dining, Kitchen, Beds, Tables & More Today!


The iphone websites showcased here are small sample of sites which has capable to display properly in all the handheld devices. If you have any mobile websites to be showcased, share with us.

Keywords to here:

  • top mobile websites
  • iphone websites
  • free mobile websites
  • websites for mobile
]]> 0
Tips: In Responsive Design how to remove content using css media queries Fri, 18 Jan 2013 07:57:02 +0000 Related posts:
  1. Android Design – Ice Cream Sandwich
  2. CSS3 Multi-column layout | CSS
  3. Play Flv enables Windows Media Player open FLV files
  4. Remove Namespace from server Side XML+as3
  5. as3 Remove all children from Display Object

To create layout which scales across multiple devices, We dont always use the same content or images across the smaller screen size devices.

It is wise to use minimal content in small screen devices. So while creating responsive design!! means loading different stylesheet pages or applying different styles for the content. We want remove some containers from the layout inside media queries CSS.



How to remove some of the text or image content from HTML page on small screen devices while using media queries?, But which is better way to do..

Applying simple css property removes the content from layout, which we are using for long time to remove content on HTML page.

We can use either one of the below in media queries css..

display: none;


visibility: hidden;


Which property is wise to use? to get rid of the content in css media queries.

CSS Property visibility: hidden;

When using the css property “visibility: hidden” we are actually hiding the content from viewing but not removed from the html page. So this is not the optimized way to use.

CSS Property display: none;

When using the CSS property “display: none”, we actually getting rid of the entire content from the screen. So this is the optimized way of removing any container from the screen when using responsive design for smaller screen devices.

Keywords to here:

  • hiding content on responsive design
  • remove image for responsive design
  • change visibility for small screen device
  • remove content for css media queries
  • media queries to remove div, image
]]> 0
QR code generator in Flash AS3 using Google charts API Tue, 04 Dec 2012 11:35:45 +0000 Related posts:
  1. AS3 + Twitter interaction code snippets | Flash
  2. TinyUrl with actionscript 3.0 | Create TinyURL with as3
  3. Create Simple Tabs in Actionscript, Flash CS5 | Tabbed Navigation
  4. AS3 + Flash Loading Variables from a Text File
  5. Send / Pass values from Flash as3 to PHP without opening new window

QR codes are seen every where from news magazine, website, web ads, commercial television advertisements. With the more usage of smart phones with IOS and Android OS capable have more apps available to decode QR codes with that we can easily open URL instead of typing the URL from news paper in mobile browser.

In this Flash action script tutorial we are going to see how to generate QR code in AS3 using Google chart API.

Tutorial difficulty:

  • Basic to Intermediate
  • Actionscript 3.0


AS3 qr generator code source 

QR Code generator in Flash AS3

Google has varities of web API for simplifying developer operations. Some of the API are

  • Google Data APIs
  • Ajax APIs
  • Ads APIs

Some of the Google Data APIs we mostly use are Google Apps, Google Analytics, Blogger, Google Base, Google Book Search, Google Calendar, Google Code Search, Google Earth, Google Spreadsheets, Google Notebook, and Picasa Web Albums.

We are going to use the Google chart API ( “” ) to pull the QR code for the URL we have passed. The QR code we are going to pull the particular URL is customizable to some extent. Few are discussed at end of the code.

Sample qr code in as3:

Below is a sample qr code for the URL:×140&cht=qr&chld=L|0&chl=

Entire Code for QR code generator

import flash.display.Loader;

var qrLoader:Loader = new Loader();
qrLoader.load(new URLRequest("|0&chl="))

qrLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event):void{

Explanation for Actionscript used:

Simple Loader instance to load the Google Chart API with following parameters.×140&cht=qr&chld=L|0&chl=


chs=x Specifies the width and height
cht=qr Specifies a qr code
chl= The data to encode.

Also check Google Chart API – QR Code details for more information.

]]> 0
Download Adobe Flash Player 11.5 and AIR 3.5 Wed, 07 Nov 2012 06:23:06 +0000 Related posts:
  1. flash player download | adobe flash player download and install
  2. Download Adobe AIR 3.2 Beta and Adobe Flash Player 11.2 Beta
  3. Adobe Flash Player 11.3 Beta available for download
  4. Download Flash Player Incubator preview
  5. Download Flash Player 11.3 Beta and AIR 3.3 Beta

Adobe has released Adobe Flash Player 11.5 and AIR 3.5  for download, which is focused primarily on security and stability enhancements and includes iOS and debugging improvements as well.

download adobe player and air sdk

Adobe Flash Player 11.5 New Features

  • Packaging multiple libraries in an ANE (iOS)
  • Debug stack trace in release builds of Flash Player
  • Invoke Event enhancement
  • Static linking of DRM (Desktop only)

Adobe AIR 3.5

Adobe AIR 3.5 provides developers with a consistent and flexible development environment for the delivery of out-of-browser applications and games across devices and platforms (Windows, Mac, iOS, Android). AIR 3.5 SDK includes:

  • Framework for Adobe AIR APIs
  • Template for the Adobe AIR application install badge
  • Command-line Adobe AIR Debug Launcher (ADL)
  • Command-line Adobe AIR Developer Tool (ADT)

Download AIR 3.5 and Flash Player 11.5

]]> 0
DETECT IOS DEVICE TILT DIRECTION USING HTML5 + JAVASCRIPT Mon, 05 Nov 2012 08:01:46 +0000 Related posts:
  1. Detect / get iPad device orientation using HTML5
  2. Create HTML5 Canvas dynamically using javascript
  3. Adding HTML5 Canvas Mouse Events using javascript
  4. Open Html popup Window in as3 using JavaScript
  5. InnerHtml is not working in FireFox and Safari.

When building game for IOS device using HTML5 we may need to detect the IOS device tilt direction to move the Car, Space ship or any Object in same direction. There are lots and lots of user interactive games or apps can be done with this. In this article we have shared the code which makes it possible to tilt programming objects to react with user action of tilting the IOS device.

Note: Please note that the code works only in IOS browser. 
Will not work on the HTML5 enabled browser in desktop.

Read the article about IOS device orientation detection using HTML5 Difficulty: Intermediate developers Tools & Programming Used:

  • HTML5
  • Javascript
  • IOS Device for Checking

IOS device tilt detection using HTML5 and Javascript:

Below code checks the IOS device tilt direction on both portrait and landscape mode of the device. Periodic checking of the device orientation or tilt was done using javascript timer function. Javascript also updates the direction, orientation and number of tilt in the HTML.


Entire Code for IOS device tilt detection:

//Code below checks the device direction and orientation and triggers the movement of gallery

	var status = 0;
	var count = 0;
	var checkTimer;

	if (window.DeviceMotionEvent==undefined) {
		 alert("Not supported on your device or browser.  Sorry.");
		checkTimer = setInterval(function(){checkDirection()},2000);

		window.ondevicemotion = function(event) {

			 ax = event.accelerationIncludingGravity.x * 5;
			 ay = event.accelerationIncludingGravity.y * 5;

			 var landscapeOrientation = window.innerWidth / window.innerHeight > 1;

			 if (landscapeOrientation)
				document.getElementById("orientationLabel").innerHTML = "Landscape";
				getDirection(ay, true);
				document.getElementById("orientationLabel").innerHTML = "Portrait";
				getDirection(ax, true);


	//True = called from device Event | False called for repeat action
	function getDirection( dir )
		if(status == 0){ //initial condition
		  status = 3; //stay
		  statusmsg = 'Tilt to Play Gallery';
		if(dir > 10 && status != 2){ //move right on device
		  status = 2;
		  statusmsg = 'Right';
		if(dir < -10 && status != 1){ //move left on device
		  status = 1;
		  statusmsg = 'Left';
		if(dir > -10 && dir < 10 && status != 3){ //device held steady
		  status = 3;
		  statusmsg = 'Tilt to Play Gallery';
		  //If device idle make count zero
		  count = 0;
		  document.getElementById("directionLabel").innerHTML = statusmsg;

	function checkDirection( )

		if(statusmsg == "Right")
			document.getElementById("directionLabel").innerHTML = statusmsg +" : "+count;


		}else if(statusmsg == "Left")

			document.getElementById("directionLabel").innerHTML = statusmsg +" : "+count;	



Code Explanation:

Initially check for device and HTML5 support

if (window.DeviceMotionEvent==undefined) {
		 alert("Not supported on your device or browser.  Sorry.");
		//Device supports

Checking the device orientation using javascript

We have discussed about the IOS device orientation detection here,

HTML for action display on screen:

<h2>Device Orientation with HTML5</h2>
Direction :<span id="directionLabel">Tilt to Play Game</span><br/>
Orientation :<span id="orientationLabel"></span>

Conclusion: We have seen simple code to detect IOS device tilt direction using Javascript+html5

]]> 0
HTML5 Image crop tool without server side using javascript Thu, 18 Oct 2012 07:23:48 +0000 Related posts:
  1. creating marching ants html5 and javascript
  2. Adding HTML5 Canvas Mouse Events using javascript
  3. Create HTML5 Canvas dynamically using javascript
  4. PHP jQuery Image crop script | ajax plugin code demo
  5. HTML5 canvas color picker + jQuery + CSS3

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>
<title>Marching ants | marquee tool in HTML5</title>

<style id="basics">
	/* Basic standard module */
	.mod {
		margin:.6em auto;
	.mod .bd {

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

		padding:0 2px;
	.marchingants2 .inner {
		background:url(images/ants.gif) repeat-x 0 -6px;
		padding:2px 0 0 0;
	.marchingants2 .hd {
		background:url(images/ants.gif) repeat-y 0 0;
	.marchingants2 .ft {
		background:url(images/ants.gif) repeat-x 0 0;

	.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;

<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.

<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.

<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 style="font-family: Verdana; font-size: 12px;">
  <p>Drag Over the Image and Press "Crop Image"</p>
  <p><a href="">link to tutorial</a></p>
  <p>By <a href=""></a></p>

<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 =;
		var top =;
		var Width =;
		var 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; = 0; = 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); = mouse.x; = mouse.y;

	var ant = document.getElementById('testAnt'); = ("px"; = ("px"; = (0)+"px"; = (0)+"px";

	 	myState.dragging = true;

  }, true);

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

    if (myState.dragging)

      var mouse = myState.getMouse(e);

	  var width =  mouse.x -;
	  var height =  mouse.y -;

	  var ant = document.getElementById('testAnt'); = ("px"; = ("px"; = (width-6)+"px"; = (height-6)+"px";
  }, true);
  canvas.addEventListener('mouseup', function(e) {
  		  myState.dragging = false;
  }, true);
  // double click for making new shapes
  canvas.addEventListener('dblclick', function(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'));


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

]]> 0