Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML5

Paint Brush Application Using HTML5 Canvas

5.00/5 (10 votes)
24 Jul 2012MIT5 min read 76.8K   4.5K  
A web based Paint Brush application using HTML5 Canvas.

Screenshot Main Page

Introduction

I think the best way of making a software application is to "develop a web-based application and host it on Cloud", then we don't have to worry about installations, as it will be easily updatable and easy to manage versions. Also our application can support different platforms like Windows, Linux, iOS, Android, etc... That means users can run apps on Tablet/Mobile PC’s too [which is very important nowadays as they are popular in the market].

There are many browser based applications on Cloud, but some of them ask for add-in or Silverlight installations, which [I reckon] are not platform independent apps, because some platforms doesn't understand add-ins or Silverlight and will not allow installations.

HTML5 technology can solve most of these issues, and this is a basic paint brush application using HTML5 and JavaScript.

Background

I gathered bits and pieces from different code sharing sites and blogs. To carry on with this tutorial, you’ll need to know a little about C#, ASP.NET, JavaScript, and client-server technology.

Please do refer www.w3schools.com to get details of properties and events of each HTML5 object.

Getting started

Download the source and executables attached to this article. Unzip zip files.

Download and install the Ajax Toolkit [AjaxControlToolkit.dll]. Copy AjaxControlToolkit.dll to the \bin folder.

You have to configure IIS to run this application. Steps to configure IIS are as follows:

  1. Open Control Panel -> Administrative Tools -> Internet Information Services (IIS) Manager. Alternatively type “inetmgr” in Start -> Run and click OK.
  2. In “Internet Information Services (IIS) Manager”, right click on Sites and “Add Web Site”.
  3. Enter Site Name [e.g.: paintbrushapp], Host Name [e.g.: mylocalmachine], Port Number [e.g.: 8080].
  4. Choose the Physical Path where we unzip the executables [path of Default.aspx].
  5. Press OK to create your website

IIS is now configured. Now enable Popup Windows and JavaScript for your default browser. Type: http://mylocalmachine:8080/ on your browser address bar and Enter. [Replace with your host name and port number.]

Now the PaintBrush application will start. [You can open the solution file [.sln] or project file [.csprj] in Visual Studio and run it]. By running this application, you will get a standalone browser window with a Canvas and toolbox on the left side. Draw, Line, and Square buttons are free draw items. You can click on the corresponding button and start drawing on the canvas.

Clicking on the Open button will open an AJAX popup window to select the image file. Choose any image file to open and click on OK. The selected image file will be loaded to canvas.

Screenshot Open File

For a new Canvas, you can adjust the width and height by clicking on the Page-Size button.

Screenshot Adjust Page Size

You can add a text into the canvas by clicking the Text button and click the desired location on canvas. Type the text on the popup box and press OK.

Screenshot Add Text

Finally you have the Save and Exit options. Clicking on Save will open an image on a new window. Either you can save the image by right click [right click and save image] or you can print it. Clicking on the Exit button will shutdown the application after confirmation by the user.

Screenshot Confirm Exit

Using the code

We are making an application, [not a website] even though it is running on the browser.

We don't need an address bar, status bar, back-forward buttons of browser. So from the Default.aspx page we are opening a new window for the application, without having all those additional stuff [PaintBrushCanvas.aspx].

C#
//
// Load Complete Event of Default.aspx Page
//
protected void Load_Complete(object sender, EventArgs e)
{
    ScriptManager.RegisterStartupScript(this.Page, this.GetType(),
                "Script", " <script  language='javascript'>" +
                " NewWin=window.open('PaintBrushCanvas.aspx',null, 'resizable=yes,menubar=no,toolbar=no," +
                " location=no,directories=no,status=no');" +
                " window.open('','_self','');" +
                " setTimeout('self.close();',1000);</script>", false);
}

Page Designing

In the PaintBrushCanvas.aspx page, we have a table with two columns: one is for the Toolbox [left] and the other for the Canvas [right].

The Canvas should be put inside a container <div id="container"> with position, overflow, and scrollbar-base-color styles defined. This will enable scroll bars, if the canvas size exceeds the screen size.

#container { position: relative; overflow: auto; scrollbar-base-color:#ffeaff;  }

Maximized State

For the initial, maximized state of our application window, we should add the below script inside the head section.

XML
<script type="text/javascript">
    window.moveTo(0, 0);
    window.resizeTo(screen.width, screen.height);
</script>

Initialization

All our JavaScript code is in the CanvasUtils.js file. All styles are defined inside the StyleSheet.css file. We should make an init() call from the onload event of the body tag to initialize our application [onload="init();"]. The Init () function will make the 2D context of our canvas object, adjust the size of the canvas and container, wire up all canvas events, and select the default tool. We have a tools array to hold all the canvas drawing tools [var tools = {};] and ev_canvas handles all mouse events of the canvas and re-directing to the selected tool function.

JavaScript
try {
if (ev.layerX || ev.layerX == 0) {  // Firefox
    ev._x = ev.layerX;
    ev._y = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) { // Opera
    ev._x = ev.offsetX;
    ev._y = ev.offsetY;
}

    // Call the event handler of the tool.
    var func = tool[ev.type];

    if (func) {
        func(ev);
    }
}
catch (err) {
    alert(err.message);
}

We use only basic canvas functions for all drawing tools, like:

  • lineTo – to draw line
  • clearRect – to clear rectangle area in canvas
  • moveTo – move active location to given pixel
  • fillText – to draw text on canvas
  • strokeRect – to draw rectangle

Canvas Layers

We have used two layers of canvas, the top level canvas is a transparent canvas.

All hand drawing tools are initially drawn on the top level [transparent] canvas and on mouse-up [that means we finished a continuous drawing]. We update to background canvas using the img_update() function and clears the temporary top level canvas.

JavaScript
function img_update() {
    contexto.drawImage(canvas, 0, 0);
    context.clearRect(0, 0, canvas.width, canvas.height);
}

Save Image/Canvas

When the user clicks on the Save button, we convert the canvas to an Image object using the toDataURL() function and open the Image in a new window:

JavaScript
var img = destinationCanvas.toDataURL("image/png");

WindowObject = window.open('', "PrintPaintBrush", "toolbars=no,scrollbars=yes,status=no,resizable=no");
WindowObject.document.open();
WindowObject.document.writeln('<img src="' + img + '"/>);
WindowObject.document.close();
WindowObject.focus();
WindowObject.print();

Points of Interest

Many software applications have started using HTML5 in their web forms for various purposes. I saw a "signature pad" in a popular CRM system for online approval process, which is developed using HTML5-Canvas.

History

  • Draft version: 24 Jul 2012.

License

This article, along with any associated source code and files, is licensed under The MIT License