Drawing with JavaScript

This post shows how to implement simple JavaScript drawing. After page is loaded, JavaScript will generate HTML table and attach onMouseDown and onMouseOver event handlers to the each table cell. When user clicks the left mouse button and move mouse pointer over table cell, table cell will change background-color property to the selected color. Please try …

Here is list of complete JavaScript source code:

// define redips object container
var redips = {};

// script configuration
redips.configuration = function () {
    redips.color = 'red'; // default colour
    redips.columns = 77; // number of colums (X)
    redips.rows = 50; // number of rows (Y)
    redips.mouse = 0; // pressed mouse button (1 when left button is pressed)
    redips.div = document.getElementById('drawing-table'); // drawing container reference
};

// script initialization
redips.init = function () {
    // apply configuration
    redips.configuration();
    // create HTML table
    redips.tableCreate();
    // attach event listener to every TD
    redips.tdEvents();
    // disable drag event for IE
    document.body.ondragstart = function (e) {
        return false;
    };
    // attach onmousedown document level
    document.onmousedown = function (e) {
        // define event
        var evt = e || window.event;
        // needed for FF to disable dragging    
        if (evt.preventDefault) {
            e.preventDefault();
        }
        // set pressed mouse button 
        if (evt.which) {
            redips.mouse = evt.which;
        }
        else {
            redips.mouse = evt.button;
        }
    };
    // attach onmouseup document level
    document.onmouseup = function (e) {
        redips.mouse = 0;
    };
};

// create table HTML and set to the DIV container
redips.tableCreate = function () {
    var tbl = '', // initialize table string
        div, // reference to the drawing table
        i, j; // local variables
    // open loops to create table rows and table cells
    for (i = 0; i < redips.rows; i++) {
        tbl = tbl + '<TR>';
        for (j = 0; j < redips.columns; j++) {
            tbl = tbl + '<TD></TD>';
        }
        tbl = tbl + '</TR>\n';
    }
    // set table HTML to the DIV element
    redips.div.innerHTML = '<TABLE cellspacing="0" cellpadding="0">' + tbl + '</TABLE>';
};

// attach event listener to every TD
redips.tdEvents = function () {
    // collect TD elements from the drawing-table DIV
    var td = redips.div.getElementsByTagName('td'),
        i;
    // loop through every TD and attach onmouseover event listener
    for (i = 0; i < td.length; i++) {
        td[i].onmouseover = redips.mouseover;
        td[i].onmousedown = redips.mousedown;
    }
};

// TD onmouseover event handler
redips.mouseover = function () {
    if (redips.mouse === 1) {
        this.style.backgroundColor = redips.color;
    }
};

// TD onmousedown event handler
redips.mousedown = function () {
    this.style.backgroundColor = redips.color;
};

// set color (input parameter is TD reference)
redips.setColor = function (obj) {
    // set table reference (first child of DIV container)
    var tbl = redips.div.firstChild;
    // set the selected colour
    redips.color = obj.style.backgroundColor;
    // set table border colour (selected colour)
    tbl.style.borderColor = redips.color;
};

// attach onload event listener
if (window.addEventListener) {
    window.addEventListener('load', redips.init, false);
}
else if (window.attachEvent) {
    window.attachEvent('onload', redips.init);
}

This short JavaScript code shows how to dynamically create HTML table and attach event handlers. After page is loaded, JS code will generate HTML table, attach onmousedown and onmouseup listeners to document level and onmouseover listener to each TD cell. And here are some points to note:

1. Border conflict resolution
If border styles differ only in colour, then a style set on a cell wins over one on a row, which wins over a row group, column, column group and, lastly, table.

Means, I have to set 2px border instead of 1px for table border because FF didn’t show table border. OK, than I removed border-collapse:collapse and FF displayed border, but unfortunately that “disturbed” IE and table cell borders disappeared in IE. Finally, when I set table border to 2px (which is different to 1px of table cell border), both browsers displayed table border and table cell border.

If you want to read more:
www.w3.org/TR/CSS21/tables.html#border-conflict-resolution

2. How to disable drag event
I have to disable drag event for IE and FF. In IE was enough to return false in body.ondragstart, while in FF I should preventDefault() method. preventDefault cancels the event (if it is cancel-able), without stopping further propagation of the event.

3. Turn off wpautop WordPress filter
This JavaScript example is saved as WordPress post (inline script). Nothing strange, but when post is generated via WordPress engine, wpautop function filters the content (puts p tags) and that breaks inline JavaScript.

The solution was to disable WordPress filtering for inserted JavaScript with the following plugin:
https://wordpress.org/plugins/wp-no-format/
http://stackoverflow.com/questions/6195635/is-breaking-the-page-in-wordpress

The trick was also to write uppercase tags in JavaScript (TABLE, TR, TD) to bypass adding NewLine by WordPress.

05/07/2015 – JavaScript code rewritten and prepared redips13.tar.gz download package

7 thoughts on “Drawing with JavaScript”

  1. Very good post here, If I may ask how such a script can be used. Do you call it from a PHP script or do you simply put this code in an HTML/PHP script?

    I am trying to create something close to a whiteboard, but I am not having any luck in coding it; so some response will be appreciated.

  2. Simon,
    this code is independent from any kind of Web platform. And as you said, you can simply put this few JavaScript lines to the HTML page. Just click to the “view plain” and copy source code to your file. Please, don’t forget to create DIV tag with id=”drawing_table” where create_table() function should generate HTML table tags. If you open HTML source of this post, search for the keyword “drawing_table” and you will see styles and needed HTML code.

  3. It’s indeed a very good post…! But I’m looking for something that is more efficient than this. I’m looking for the help about drawing charts and graphs in the browser from the data in the database.

  4. Dbunic,
    How would you go about saving an image from this black-board to a database or sending it by e-mail?
    It’s a very nice script, by the way.
    Thanks.

  5. @Lenny – Drawn image is actually HTML, so I suppose that saving innerHTML of TABLE node should not be a problem. The same is with sending it in e-mail. ;)

  6. nice script. can we create image from this drawing board and save that image ?

  7. @Vasim Padhiyar – This script is only for demo. My intention was to show how to use table for drawing (attach onmouseover event handler to table cells and to change selected color when mouse pointer is over cell). On the other hand, now in HTML5 era, drawing in browsers is much easier using canvas element and canvas element has ready method to save drawn images – toDataURL(). Here is answer how to save HTML5 canvas.

Leave a Comment