Skip to content

Instantly share code, notes, and snippets.

@thomasjao
Created August 4, 2015 17:02
Show Gist options
  • Save thomasjao/2a6820c070a9cbead46a to your computer and use it in GitHub Desktop.
Save thomasjao/2a6820c070a9cbead46a to your computer and use it in GitHub Desktop.
Dynamically Add Shape/Path in SVG area
// Following snippet is the basice to add a new shape to an SVG area
var svg = document.getElementById('svg');
var rect = document.createElementNS('http://www.w3.org/2000/svg'); // Note: Using createElementNS() instead of createElement()
rect.setAttributeNS(null, 'x', xValue );
rect.setAttributeNS(null, 'y', yValue );
rect.setAttributeNS(null, 'width', widthValue );
rect.setAttributeNS(null, 'height', heightValue );
rect.setAttributeNS(null, 'style', 'fill: none; stroke: blue; stroke-width: 1px;');
svg.appendChild( rect );
// For existing shape, draw a rectangle around the shape
var pane = { x: svg.offsetLeft, y: svg.offsetTop }; // svg offset: svg coordinate relative to screen coordinate
var target = document.getElementById('targetID');
var boundingRect = target.getBoundingClientRect();
var rect1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect1.setAttributeNS(null, 'x', boundingRect.left); // NOTE: there is no pane translate needed, getBoundingClientRect() return coordinate
rect1.setAttributeNS(null, 'y', boundingRect.top); // relative to it's parent node (at this example: SVG)
rect1.setAttributeNS(null, 'width', (boundingRect.width - 2*pane.x)); // Also NOTE: use setAttributeNS instead of setAttribute
rect1.setAttributeNS(null, 'height', (boundingRect.height - 2*pane.y));
rect1.setAttributeNS(null, 'style', 'fill: none; stroke: cyan; stroke-width: 1px;');
svg.appendChild(rect1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment