Create a shape from a DOM node

Our SVG shapes can sometimes be too complex to code by hand.

Luckily for us, Wilderness can create Shapes from DOM nodes.

Let's assume that in our HTML we have an SVG with a circle defined.


<svg width="100" height="20" viewBox="0 0 100 20">
  <circle cx="50" cy="10" r="10" fill="#DBF8A1"></circle>
</svg>
    

When creating a Shape, we can automatically generate attributes by passing a DOM node to the el property of a Plain Shape Object.


import { shape, render } from 'wilderness'

const svg = document.querySelector('svg')
const circle = svg.querySelector('circle')

const plainShapeObject = {
  el: circle,
  fill: '#1F9FFD'
}

const circleClone = shape(plainShapeObject)

render(svg, circleClone)
    

If we pass additional properties to a Plain Shape Object, as we have with the fill property in the example above, these will add to or overwrite the properties automatically generated from the DOM node.

The example above is equivilent to the following hand-coded example.


import { shape, render } from 'wilderness'

const plainShapeObject = {
  type: 'circle',
  cx: 50,
  cy: 10,
  r: 10,
  fill: '#DBF8A1',
  fill: '#1F9FFD'
}

const circle = shape(plainShapeObject)

render(document.querySelector('svg'), circle)
    

Replace an existing DOM node

Another thing that can be useful is to replace an existing DOM node with a Shape.

The shape function takes a final argument of options. One of these options is the replace property. This allows us to define a DOM node that the Shape will replace when rendered.


import { shape, render } from 'wilderness'

const svg = document.querySelector('svg')
const circle = svg.querySelector('circle')

const plainShapeObject = {
  el: circle,
  fill: '#1F9FFD'
}

const circleClone = shape(plainShapeObject. { replace: circle })

render(svg, circleClone)
    

This time, our cloned circle will replace the existing DOM node when rendered, instead of being appended alongside it.