Drawing on SVG element

I could not find any tutorialsĀ on how to do this, or examples, and the only thing I could find that did the same was a huge program with tons of code to wade through (SVGedit). It’s very easy to draw on an SVG element, right in your browser.

You will need:

An SVG element in your HTML

The basic idea is:

Get the SVG element.
Get the Mouse Coordinates.
Create a PATH element dynamically in the SVG.
Then use getAttribute() and setAttribute() on the path.

Here’s the code:

var isdrawing = false;
var currentpath;

function getlocalmousecoord(svg, evt){

  //calculate mouse coordinates
    var pt = svg.createSVGPoint();
    pt.x = evt.clientX;
    pt.y = evt.clientY;
    var localPoint = pt.matrixTransform(svg.getScreenCTM().inverse());
    localPoint.x = Math.round(localPoint.x);
    localPoint.y = Math.round(localPoint.y);
    console.log("mouse at " + pt.x + "," + pt.y  + " (global)  "+ localPoint.x + "," + localPoint.y+" (local)");

    return localPoint;

var svg = document.getElementsByTagName('svg')[0];
$( document ).ready(function() {
    console.log( "Jquery ready!" );

//grab the first SVG element on the page
var svg = document.getElementsByTagName('svg')[0];  /*http://stackoverflow.com/questions/4850821/svg-coordinates-with-transform-matrix  */

//Mousedown event handler
   isdrawing = true;
    var localPoint = getlocalmousecoord(svg,evt);
    var newElement = document.createElementNS("http://www.w3.org/2000/svg", 'path'); //Create a path in SVG's namespace
    currentpath = newElement;
    newElement.setAttribute("d", " M " + localPoint.x + " " + localPoint.y ); 
    newElement.setAttribute("fill", "transparent"); 
    newElement.style.stroke = "#f00"; //Set stroke colour
    newElement.style.strokeWidth = "5px"; //Set stroke width

   isdrawing = false;
  if(isdrawing == true){
  //calculate mouse coordinates
      var localPoint = getlocalmousecoord(svg,evt);

      var pathstring = currentpath.getAttribute("d");
      pathstring = pathstring + " L " + localPoint.x + " " + localPoint.y ;
});  //end of .ready

(Someday I will figure out how to preserve line breaks yet not wrap in wordpress)


Here is the working example:



Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.