Click here to Skip to main content
Click here to Skip to main content

Paint Brush Application Using HTML5 Canvas

, 24 Jul 2012
Rate this:
Please Sign up or sign in to vote.
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].

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

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

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.

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:

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

About the Author

derinpdavis
Software Developer
Australia Australia
- Software Developer (since 2K)
- Has Bachelor & Master degree in Computer Applications [BCA & MCA]
- Programmed with C, C++, VB, C#, ASP.NET, XAML/WPF
- Developmentt of Apps for Android on Eclipse
- Enthusiastic on LINQ, XML, HTML5
- Love to develop on Web / Cloud
Follow on   Twitter   Google+

Comments and Discussions

 
QuestionExcellent work, but I have one question PinprofessionalHamidYaseen19-Apr-14 23:20 
QuestionExcellent PinprofessionalHamidYaseen29-Mar-14 3:26 
AnswerRe: Excellent Pinmemberderinpdavis16-Apr-14 19:04 
QuestionWoops here is my vote of 5!! PinmemberAkshay Srinivasan215-Aug-12 11:16 
AnswerRe: Woops here is my vote of 5!! Pinmemberderinpdavis16-Aug-12 16:41 
QuestionMy Vote of 5: Very nice Paintbrush app exploiting HTML5 canvas PinmemberAkshay Srinivasan215-Aug-12 11:13 
Question\bin folder should have AjaxToolkit.dll & PaintBrushHtml5Canvas.dll Pinmemberderinpdavis26-Jul-12 13:57 
QuestionLooks cool, trying, but missing file(s), I think Pinmembernewton.saber25-Jul-12 5:54 
The demo doesn't seem to contain the code-behind files: (...aspx.cs)
Here's the error I get:
 
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
 
Parser Error Message: Could not load type 'PaintBrushHtml5Canvas.Default'.
 
Source Error:
 

Line 1:  <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PaintBrushHtml5Canvas.Default"
Line 2:      OnLoadComplete="Load_Complete" %>
Line 3:

AnswerRe: Looks cool, trying, but missing file(s), I think Pinmemberderinpdavis25-Jul-12 11:59 
AnswerRe: Looks cool, trying, but missing file(s), I think Pinmemberderinpdavis26-Jul-12 13:56 
GeneralRe: Looks cool, trying, but missing file(s), I think Pinmembernewton.saber27-Jul-12 2:08 
QuestionMessage Removed Pinmembermxhfdaia24-Jul-12 14:48 
AnswerRe: welcome to: http://www.netetrader.com Pinmemberderinpdavis24-Jul-12 14:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140709.1 | Last Updated 24 Jul 2012
Article Copyright 2012 by derinpdavis
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid