Paint

by Harvey_He

HTML

<p><label>Drawing tool: <select id="dtool">
    <option value="line">Line</option>
    <option value="rect">Rectangle</option>
    <option value="pencil">Pencil</option>
    </select></label></p>

<div id="container">
    <canvas id="imageView" width="400" height="300">
    </canvas>
</div>
<script>
    // Keep everything in anonymous function, called on window load.
    if (window.addEventListener) {
    window.addEventListener('load', function() {
    var canvas, context, canvaso, contexto;
    
    // The active tool instance.
    var tool;
    var tool_default = 'line';
    
    function init() {
    // Find the canvas element.
    canvaso = document.getElementById('imageView');
    if (!canvaso) {
    alert('Error: I cannot find the canvas element!');
    return;
    }
    
    if (!canvaso.getContext) {
    alert('Error: no canvas.getContext!');
    return;
    }
    
    // Get the 2D canvas context.
    contexto = canvaso.getContext('2d');
    if (!contexto) {
    alert('Error: failed to getContext!');
    return;
    }
    
    // Add the temporary canvas.
    var container = canvaso.parentNode;
    canvas = document.createElement('canvas');
    if (!canvas) {
    alert('Error: I cannot create a new canvas element!');
    return;
    }
    
    canvas.id = 'imageTemp';
    canvas.width = canvaso.width;
    canvas.height = canvaso.height;
    container.appendChild(canvas);
    
    context = canvas.getContext('2d');
    
    // Get the tool select input.
    var tool_select = document.getElementById('dtool');
    if (!tool_select) {
    alert('Error: failed to get the dtool element!');
    return;
    }
    tool_select.addEventListener('change', ev_tool_change, false);
    
    // Activate the default tool.
    if (tools[tool_default]) {
    tool = new tools[tool_default]();
    tool_select.value = tool_default;
    }
    
    // Attach the mousedown, mousemove and mouseup event listeners.
    canvas.addEventListener('mousedown', ev_canvas, false);
   ...

CSS

* {
    -webkit-user-select: none;
    -webkit-transform: translate3d(0,0,0);
}
canvas { cursor: crosshair; }
#container { position: relative; }
#imageView { border: 1px solid #000; }
#imageTemp { position: absolute; top: 1px; left: 1px; }