Rotate an ASP.NET Image Control using HTML 5 Canvas

Posted by: Suprotim Agarwal , on 12/16/2011, in Category ASP.NET
Views: 164149
Abstract: The Canvas element is an HTML tag that you can embed inside an HTML document, for the purpose of drawing graphics, via a JavaScript API. In this article, we will see how to use the HTML 5 canvas element to rotate an Image served by the ASP.NET Image Control.
The HTML5 canvas is one of the oldest HTML 5 elements. Introduced by Apple Inc. initially in 2004, the Canvas element made its way into the first HTML 5 draft specification. The Canvas element is an HTML tag that you can embed inside an HTML document, for the purpose of drawing graphics, via a JavaScript API.

In this article, we will see how to use the HTML 5 canvas element to rotate an Image served by the ASP.NET Image Control.

 

Step 1: Open VS 2010 and create an ASP.NET Website. Set it’s target schema for validation as HTML 5 by going to Tools > Options > Text Editor > HTML > Validation

html5-visualstudio-schema

If you do not see the HTML 5 option, make sure you have installed Visual Studio 2010 Service Pack 1 and Web Standards Update for Microsoft Visual Studio 2010 SP1.

Step 2: Declare the following markup

html5-aspnet-image

As you can see, we have declared an HTML 5 canvas element of dimensions 400x400 and an ASP.NET Image control with display set to none. I will explain shortly, why the display is set to none.

Step 3: Now declare the following JavaScript code inside the <head> element

html5 canvas Rotate

Let us understand this code line by line

html5-canvas-context

The window.onload is to wait for the page to load before trying to access the canvas tag by its ID. To draw on the canvas, we need a reference to it. We have used getElementById to get this reference from the DOM. We then set a  variable context to reference the 2D context of the canvas, which is used for all drawing purposes. In other words, we are asking the Canvas to give us a context to draw on.

Note: If you are wondering if there is 3D context too, then the answer is not yet! Take a look at WebGL and SceneJS.

The next line of code, references the asp.net image control in JavaScript using ClientID. We have also declared the width and height variables for the image. Do not set the image width and height in the mark up, since you have set the display property to none.

asp.net-image-javascript

The final step is to rotate the image

html5-context-properties

We are using a translate transform to move the center point of the coordinate system, which is in the top-left corner of the canvas (0,0). We have to move the center position because we have to rotate the canvas context by 45 degrees, around this current position. After moving the center point, it is now (200,200).

Note: the canvas.width and height is 400 and 400/2 = 200.

After moving your reference point to (200,200), we are now centering our image over that point, by calling the drawImage() method. We are drawing the image from above and to the left, of your current reference point.

context.drawImage(img, x, y, width, height)

This function makes a 200 × 200 pixel box for the image, with the top-left corner at point (-100,-100).

The last step is to set the image source to the desired image. The reason we set the display property of the ASP.NET image control to none is to avoid displaying the image twice; once where the image control is declared outside the canvas and second, where we are drawing the image inside the canvas.
HTML 5 Rotate demo

Detecting Browser Support and Graceful Degradation

The latest versions of  IE (9 onwards), Firefox, Safari, Chrome and Opera all provide reasonably good support for the Canvas element. However for users who are using older browser versions, we can easily detect browser support or gracefully display a message, if the user’s browser does not support Canvas. For eg: to check if your browser supports canvas and the getContext method exists, change the line of code to:

check-context-canvas

Wrap the above code in a try-catch block for handling exceptions. HTML 5 provides a nice way to handle browsers that do not support HTML 5. This is done by adding a piece of text inside the Canvas element saying that the users browser does not support this feature. Every time the browser sees an element it doesn’t recognize, it displays any text contained within it as a default behavior. That’s graceful! Use this for displaying simple messages. If you want to perform a more advanced action, such as redirecting the user, use JavaScript.

html5-canvas-nosupport

There’s yet another approach to detect HTML 5 feature support on browsers, which I use often in my HTML 5 apps. Modernizr is a JavaScript library that detects the availability of HTML5 (and CSS3) features.

modernizr-canvas

The entire source code of this article can be downloaded over here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Content Management Simi Valley on Saturday, December 17, 2011 6:29 AM
thanks for this!
Comment posted by Richard on Sunday, December 18, 2011 4:30 AM
Why bother with this pathetic, childish examples. Who cares about crap?? This crap is just about you putting your face in the asp.net website, is not meant to be a tutorial of any benefit to anybody. If you want to really help the community provide tutorials that are meaningful in a real world scenario.
by the way the email is fake but the comments aren't.
Comment posted by Yoyo on Sunday, December 18, 2011 11:34 AM
Looks like a well written article, but you really should put a link to a demo before diving into the technical. Can you send a link?
Comment posted by Suprotim Agarwal on Sunday, December 18, 2011 1:06 PM
Thanks for the feedback Yoyo! I have updated the article with a screenshot and the code for demo can be found here http://www.dotnetcurry.com/Uploads/ASPNET/ASPRotateCanvas.zip
Comment posted by jack on Sunday, December 18, 2011 8:42 PM
Thanks for sharing. The it is quite easy to rotate an image in html5
Comment posted by Derp on Monday, December 19, 2011 12:28 PM
The asp:image tag's ImageUrl will not be available to server-side code because you've set it with JavaScript, so why bother with asp:image when you could just use img?  If you need to set an image path via server-side code, then the asp:image ImageUrl would already be set, and you could use imgObj.src=imgObject.src+'?rotate'; to trigger the rotation script.
Comment posted by Nick on Monday, December 19, 2011 10:56 PM
I disagree with Derp and I am not sure what he means when he says ImageUrl will not be available in JS. The purpose of the ImageUrl is to set the path to the image and that can be done using document.getElementById("<%= imageCtrl.ClientId %>").src = "...";

We are doing something similar in our application (we are using jquery too) where we have an asp.net image control and perform manipulations on it using client code. We have used a lot of code and have been thinking to use HTML 5. This article makes a lot of sense to me.

I wish the author had also shown how to save the rotated image!
Comment posted by Saboor998 on Tuesday, December 20, 2011 3:24 AM
Thanks
Comment posted by Jaykung on Wednesday, December 21, 2011 2:33 AM
Richard, this is just a little snippet that you can be useful in some situation that you can't even think of it with your own brain. You wrote that this article is childish but i see childish comment style from you instead.
Comment posted by Piyush Chandra on Friday, January 6, 2012 2:37 AM
Hi,

I was reading your article and I would like to appreciate you for making it very simple and understandable. This article gives me a basic idea of Dynamically loading image in Image control in ASP.NET and it helped me a lot. I had found another nice post over the internet which also have a wonderful explanation on Dynamically loading image in Image control in ASP.NET, for more details of that post you may visit this url...
http://www.mindstick.com/Articles/c98d98d1-3186-4cac-9069-304b08a269d3/?Dynamically%20loading%20image%20in%20Image%20control%20in%20ASP.NET

Thank you very much for your precious post.
Comment posted by roshan on Tuesday, January 17, 2012 6:07 AM
jhjghjghj
Comment posted by bozzetti giovanni on Tuesday, February 14, 2012 4:39 AM
Sorry, i don't understand anything. I programs from 25 years, but every time i try to do something i do it in hours/days not in seconds as you. If i do. I cannot believe you exist. Here in Italy we cannot do nothing in 5" seconds as you. May you help me to raise to your level ?
Comment posted by zxczxczx on Wednesday, January 30, 2013 10:46 PM
xxbdfbbdb