Development – Leet 4 Life

Software Development Code Samples and More

Skip to: Content | Sidebar | Footer

HTML5 Canvas and ASP.NET Image Control

5 December, 2012 | ASP.NET, HTML5 | By: Michael Adams

I was playing with the HTML5 Canvas element trying to allow client side zooming/panning/rotating of an image. I finally figured out an implementation that will accommodate the zooming and I am still working on the panning/rotating pieces of the functionality. I use a SELECT element to act as the scale (Zoom) for the image. Even though it is not present in the code snippet below, I use a Generic Handler to populate my ASP.NET Image control. The HTML5 canvas uses the ASP.NET Image control as the source of the image and then I can use JavaScript and the Canvas element to manipulate the image on the client side.

<select id="ZoomSelect" onchange="drawpicture();">
   <option id="Zoom50" value=".5">50%</option>
   <option id="Zoom75" value=".75">75%</option>
   <option id="Zoom100" value="1" selected="selected">100%</option>
   <option id="Zoom125" value="1.25">125%</option>
   <option id="Zoom150" value="1.5">150%</option>
   <option id="Zoom175" value="1.75">175%</option>
   <option id="Zoom200" value="2">200%</option>
<canvas id="viewer"></canvas>
<asp:Image ID="imgViewer" runat="server" style="display:none;" />

The JavaScript:

window.onload = function () {
function drawpicture() {
   var canvas = document.getElementById("viewer");
   var context = canvas.getContext("2d");
   var imageObj = document.getElementById('<%= imgViewer.ClientID %>');
   var scale = $('#ZoomSelect option:selected').val();
   context.clearRect(0, 0, 3000, 3000); // clear canvas for re-draw
   context.canvas.width = imageObj.width * scale;
   context.canvas.height = imageObj.height * scale;
   context.drawImage(imageObj, 0, 0, imageObj.width, imageObj.height, 0, 0, imageObj.width * scale, imageObj.height * scale);

Code Originally Posted Here

Write a comment