Create a shape

Basic shapes

In this lesson we're going to use Wilderness to hand-code an SVG circle, and then render it to an HTML page.

Firstly, we need a way to define shapes – their type, dimensions and color. This is done with a basic javascript object, which in Wilderness we call a Plain Shape Object.


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

The code above defines a green circle. However, as it's only a javascript object, it isn't of much use on its own.

This is where the shape function comes in.

The job of the shape function is to create a Shape. A Shape can be rendered, placed on a timeline, and animated.

At its most basic, the shape function takes a Plain Shape Object as a single argument.


import { shape } from 'wilderness'

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

const circle = shape(plainShapeObject)
    

We've now created our first Shape, and assigned it to a variable named circle. Pretty simple so far, right?

This Shape can be rendered to an HTML page using the render function.


import { shape, render } from 'wilderness'

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

const circle = shape(plainShapeObject)

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

Voila! We have created our first SVG shape, and added it to the DOM, with Wilderness.

Notice that the render function's first argument is a DOM node. This is the parent node to which we wish to append our circle.

If we want to render multiple Shapes, we simply add additional arguments to the render function.


render(document.querySelector('svg'), shape1, shape2, shape3)
    

Group shapes

The process to create group shapes is identical to that of a single shape. The only difference is that our Plain Shape Object should follow the SVG points specification for group shapes.

Let's create a tree!


const plainShapeObject = {
  type: 'g',
  shapes: [
    {
      type: 'polygon',
      points: '48 10 48 27 50 28 52 27 52 10 50 11',
      fill: 'hsl(40,20%,25%)'
    },
    {
      type: 'polygon',
      points: '48 10 48 27 50 28 50 11',
      fill: 'hsl(40,20%,15%)'
    },
    {
      type: 'polygon',
      points: '50 0 60 5 60 15 50 20 40 15 40 5',
      fill: 'hsl(90,50%,60%)'
    },
    {
      type: 'polygon',
      points: '60 5 60 15 50 20 50 10',
      fill: 'hsl(90,50%,45%)'
    },
    {
      type: 'polygon',
      points: '50 10 50 20 40 15 40 5',
      fill: 'hsl(90,50%,35%)'
    }
  ]
}

const tree = shape(plainShapeObject)

render(document.querySelectorAll('svg'), tree)
    

We've learned how to create and render an SVG shape with Wilderness. Next up let's learn how to animate a shape!