Simple Raphael Canvas

by jamesdh

HTML

<script src="http://github.com/DmitryBaranovskiy/raphael/raw/master/raphael-min.js"></script>
<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
        <script type="text/javascript" src="https://raw2.github.com/DmitryBaranovskiy/raphael/master/raphael.js"></script>
        <script type="text/javascript" src="https://raw2.github.com/ElbertF/Raphael.Export/master/raphael.export.js"></script>                
        <script type="text/javascript" src="https://raw2.github.com/crccheck/raphael-svg-import-classic/master/raphael-svg-import.js"></script>
    </head>
    <body>    
        <div id="container"></div>
        <div id="hiddenSVG"></div>
        <input type="button" id="import" value="Import SVG"></input>
        <input type="button" id="export" value="Export SVG"></input>
        <textarea id="output"></textarea>
    </body>
</html>

CSS

#container {
    width:500px;
    height: 400px;
    border:1px solid;
}

#hiddenSVG {
    width: 0;
    height: 0;
    display: none;
}

#output {
    bottom: 0;
    width: 100%;
}

JavaScript

// Found at http://lynx.io/article/simple-drawing-application-raphaeljs
window.onerror = function(msg, url, line) {
    $('#output').val(msg + ": " + url + " (line #" + line + ")");    
}

var canvas = document.getElementById('container'),
    paper = new Raphael(canvas),
    colour = 'black',
    mousedown = false,
    width = 4,
    lastX, lastY, path, pathString;

$(canvas).bind('mousedown touchstart', function (e) {
    mousedown = true;

    var x = e.offsetX,
        y = e.offsetY;

    pathString = 'M' + x + ' ' + y + 'l0 0';
    path = paper.path(pathString);
    path.attr({
        'stroke': colour,
        'stroke-linecap': 'round',
        'stroke-linejoin': 'round',
        'stroke-width': width
    });

    lastX = x;
    lastY = y;
});

$(canvas).bind('mouseup touchend', function() {
     mousedown = false;   
});

$(canvas).bind('mousemove touchmove', function (e) {
    if (!mousedown) {
        return;
    }

    var x = e.offsetX,
        y = e.offsetY;

    pathString += 'l' + (x - lastX) + ' ' + (y - lastY);
    path.attr('path', pathString);

    lastX = x;
    lastY = y;
});

$(document).keydown(function (e) {
    if (e.keyCode > 48 && e.keyCode < 58) {
        width = e.keyCode - 48;
    }
});

$("#export").click(function() {
    var svg = paper.toSVG();
    $("#output").val(svg);
});
$("#import").click(function() {
    var svg = $("#output").val();
    var svgNode = $("#hiddenSVG").html(svg)[0];
    paper.importSVG(svgNode);
});