Why Origamijs?

For many developers, learning the canvas API can be challenging. But the learning curve might be reduced with a few simplifications: a chainable canvas, stylization of objects using familiar CSS notation, and easy access to the context using selectors.

Origami began as a project to teach javascript and geometry to children and today has been used to simplify the way we work with canvas (currently only in the 2d context, but in the future it will also support WebGL).

Styling with CSS

For those who use native canvas, you need to adapt to a different way to apply styles to a shape. The origami.js lets you use the CSS notation in a javascript object to use and apply on a shape.

Let’s see:

<canvas class="canvas-class"></canvas>

var style = {
  color: '#000',
  font: '70px Helvetica',
  align: 'center',
  border: '2px solid gold'
};

origami('.canvas-class')
  .text("Nice!", 100, 100, style)
  .text("Really Nice!", 150, 150, style)

origami.draw();

You can use pure CSS to style a shape. See Shape.

Component Ecosystem

The Origamijs let you to create components based on the OrigamiContext and CanvasContext2D, enabling the use of components stateless and isolated to be reused:

origami.createComponent('Header', function(octx, props) {
  var style = {
    color: '#000',
    font: '70px Helvetica',
    align: 'center',
    border: '2px solid gold'
  };

  octx.text(props.text, 200, 100, style);
})

origami('#canvas-id')
  .Header({text: 'Random Text'})
  .draw();

You can render each of these components in SVG or another format, read about plugins to know more.

Smart Coordinates

Available for the following methods: rect, arc, image

Based on Canvas Axis ( x = right, left, center | y = top, bottom, center )

origami('.rect')
  .rect('left', 'top', 20, style)
  .rect('center', 'top', 20, style)
  .rect('right', 'top', 20, style)

  .rect('left', 'center', 20, style)
  .rect('center', 'center', 20, style)
  .rect('right', 'center', 20, style)

  .rect('left', 'bottom', 20, style)
  .rect('center', 'bottom', 20, style)
  .rect('right', 'bottom', 20, style)

  .draw();

Getting Started

Obtaining Origami.js

First of all, get Origami.js using Download Option or via package manager.

To get using Bower just run this command

bower install origamijs

Or get using NPM just run this command

npm install origamijs

Add the source before body tag end:

<script src="origami.min.js"></script>
</body>

Shapes

Draw

Method that performs the operation of drawing the current OrigamiContext queue.

octx.draw(delay)

Parameters

delay • (optional) Execute after a specified number of milliseconds. Tip: 1000 ms = 1 second.

origami('#canvas')
  .background('#330031')
  .arc('center', 'center', 50, {
      background: '#180019',
      borderSize: '4px',
      borderColor: '#FFF',
      borderStyle: 'dotted'
  })
  .draw();

Rect

Creates a path for a rectangle at position (x, y) with a size that is determined by width and height.

octx.rect(x, y, width, height)

Parameters

x • The x axis of the coordinate for the rectangle starting point.

y • The y axis of the coordinate for the rectangle starting point.

width • The rectangle’s width.

height • The rectangle’s height.

style • The style object.

origami('.canvas')
  .rect(80, 60, 50, 100, {
    background: 'lightblue',
    border: '4px solid #999'
  })
  .rect(150, 70, 40, {
      background: 'lightgreen',
      border: '4px dashed green'
  })
  .rect(20, 70, 40, 80, {
      background: '#330031',
      border: '10px dotted #af79a5'
  }).draw();

Line

Connects the points (for each point argument) in the sub-path to the x, y coordinates with a straight line.

octx.line(...arguments)

Parameters

point • The point in current line, which is a object with x and y keys.

style • The style object.

var styleLine = {
  border: '2px dotted #E40068'
};

origami('canvas#line')
  .line({x: 40, y: 50}, {x: 200, y: 50},  styleLine)
  .line({x: 40, y: 50}, {x: 300, y: 70},  styleLine)
  .line({x: 40, y: 50}, {x: 400, y: 100}, styleLine)
  .line({x: 40, y: 50}, {x: 500, y: 140}, styleLine)
  .draw();

Arc

Adds an arc to the path which is centered at (x, y) position with radius r starting at startAngle and ending at endAngle going in the given direction by anticlockwise (defaulting to clockwise).

octx.arc(x, y, radius, style, startAngle, endAngle, anticlockwise)

Parameters

x • The x axis of the coordinate for the arc starting point.

y • The y axis of the coordinate for the arc starting point.

radius • The arc’s radius.

style • The style object.

startAngle • (optional) The angle at which the arc starts, measured clockwise from the positive x axis and expressed in radians.

endAngle • (optional) The angle at which the arc ends, measured clockwise from the positive x axis and expressed in radians.

anticlockwise • (optional) If true, causes the arc to be drawn counter-clockwise between the two angles. By default it’s drawn clockwise.

origami('canvas#arc')
  .background('#720034')
  .arc(200, 100, 80, {
    background: '#E40068',
    border: '10px solid #E9E9E9'
  })
  .arc(400, 100, 80, {
    background: '#E40068',
    border: '8px dotted #E9E9E9'
  })
  .arc(300, 100, 80, {
    background: '#E40068',
    border: '6px dashed #E9E9E9'
  })
  .draw();

Polygon

Connects the points (for each point argument) in the sub-path to the x, y coordinates with a transparent line, on the draw process will fill the generated shape.

octx.polygon(...arguments)

Parameters

point • The point in current line, which is a object with x and y keys.

style • The style object.

origami('canvas#polygon')
  .polygon({x: 200, y: 160}, {x: 300, y: 40}, {x: 400, y: 160},
    {background: '#2A80B9'})
  .draw();

Border

origami('#canvas')
  .border({
      border: '4px dotted #654'
    })
  .draw();

Shape

CSS properties:

.pac-man {
  position: absolute;
  top: 40px;
  left: 20%;
  width: 0px;
  height: 0px;
  border-right: 60px solid transparent;
  border-top: 60px solid #330031;
  border-bottom: 60px solid #330031;
  border-left: 60px solid #330031;
  border-top-right-radius: 60px;
  border-top-left-radius: 60px;
  border-bottom-right-radius: 60px;
  border-bottom-left-radius: 60px;
}

Load Styles and apply style rules on Shape (empty object canvas):

origami('#canvas-id')
  .styles('.pac-man')
  .shape('.pac-man')
  .draw();

Text

Fills a given text at the given (x,y) position.

octx.text(text, x, y, style)

Parameters

text • The text.

x • (optional) The x axis of the coordinate for the text block starting point.

y • (optional) The y axis of the coordinate for the text block starting point.

style • The style object.

origami('canvas#text')
  .background('#720034')
  .text("Canvas", 140, 180, {
    color: '#E40068',
    font: '60px Helvetica',
    align: 'center',
    border: '2px solid #330031'
  })
  .text("Rocks!!", 480, 180, {
    color: '#330031',
    font: '140px Helvetica',
    align: 'center',
    border: '2px dotted #E40068'
  })
  .text("origamijs", 120, 115, {
    color: '#FFF',
    font: '50px Arial'
  })
  .draw()

Image

octx.text(imgSrc, x, y, width, height)

Parameters

imgSrc • The Image source.

x • (optional) The x axis of the coordinate for the image block starting point.

y • (optional) The y axis of the coordinate for the image block starting point.

width • The image width.

height • The image height.

origami('.canvas').image('images/origamijs.png', 10, 10)

// Or
var img = document.querySelector('#my-image');
origami('.canvas').image(img, 10, 10, width, height)

Load

When you use images, external resources if you do not load them. The script cannot run. The load method expects to obtain these resources when not cached.

origami('.canvas')
  .image('images/dog.jpg')
  .load(function(canvas) {
    canvas.draw();
  })

Clear

Alias to CanvasRenderingContext2D.clearRect(0, 0, canvas.width, canvas.height)

origami('.one').clear()

Background

Set canvas background color

origami('#demo-1').background('#2A80B9')

CanvasCtx

Get CanvasRenderingContext2Dcanvas from specified canvas

var ctx = origami('#canvas').canvasCtx(); // CanvasRenderingContext2Dcanvas

// After loaded you can use without specify selector/context
console.log(ctx) // CanvasRenderingContext2Dcanvas from '#canvas'

// You can use origami with contextObject too :)
origami(ctx).canvasBackground('blue');

Composition

Sets the type of compositing operation to apply when drawing new shapes, where type is a string identifying which of the compositing or blending mode operations to use.

Alias to CanvasRenderingContext2Dcanvas.globalCompositeOperation

Default is source-over.

origami('#my-canvas').composition('source-in')

Translate

The translate() method remaps position on the canvas.

Options:

center • canvas center position.

reset • canvas x: 0, y: 0 coordinates.

origami('#my-canvas').translate('center');

// OR

origami('#my-canvas').translate(10, 50);

// OR

origami('#my-canvas').translate(); // Equals: reset

Flip

Default: horizontal

Options: vertical, horizontal

origami('#demo-1')
  .image('images/person.jpg', 0, 0, 200, 200)
  .flip('horizontal')
  .image('images/person.jpg', 0, 220, 200, 200)
  .flipEnd()
  .flip('vertical')
  .image('images/person.jpg', 220, 0)
  .flipEnd()
  .load(function(canvas) {
    canvas.draw();
  })

Rotate

The rotate() method rotates the current drawing. The rotation will only affect drawings made after the rotation is done.

Default: slow

Options: slow, normal and fast

origami('#my-canvas').rotate(degrees);

Opacity

Specifies the alpha value that is applied to shapes and images before they are drawn onto the canvas. The value is in the range from 0.0 (fully transparent) to 1.0 (fully opaque).

var style = {
  background: 'red',
  borderSize: '4px',
  borderColor: '#FFF',
  borderStyle: 'dotted'
};

origami('#my-canvas')
  .arc(80, 100, 50, style)
  .opacity(0.6)
  .arc(200, 100, 50, style)
  .opacity(0.3)
  .arc(320, 100, 50, style)
  .opacity(0.1)
  .arc(440, 100, 50, style)
  .draw();

Restore

Restores the most recently saved canvas state by popping the top entry in the drawing state stack. If there is no saved state, this method does nothing.

origami('#my-canvas').restore();

Save

Saves the entire state of the canvas by pushing the current state onto a stack.

origami('#my-canvas').save();

On

Wrapper to addEventListener

origami(".canvas-class").on('click', clickEvent)

function clickEvent(e) {
  console.log(e.pageX, e.pageY);
}

Animation

Sprite

frames • required, default: {total: 0, animation: true}

src • required

speed • optional

loop • optional, default: true

origami('#demo-1')
  .background('#2A80B9')
  .sprite(310, 50, {
    src: '/assets/images/examples/coin-sprite.png',
    frames: {
       total: 10
    },
    speed: 60
  }).load(function(octx){
    octx.draw();
  })

Start Render

Causes execution of a callback (using requestAnimationFrame).

origami('#demo-1').startRender(frame)

Stop Render

Stop rendering animation

origami('#demo-1').stopRender()

If you want to play the stopped animation, you must to use able method before startRender, example:

origami('#demo-1').play().startRender(frame)

Examples

1: “An animated solar system”

This example animates a small model of our solar system (based on example of MDN on translation and rotation).

function draw() {
  origami('canvas#animation-1')
    .background('black')
    .composition('destination-over')
    .clear()
    .save()
    .translate(370,150)
    .rotate('slow')
    .translate(105,0)
    .image('images/Canvas_earth.png', -12, -12)
    .save()
    .restore()
    .save()
    .rotate('fast')
    .translate(0, 28.5)
    .image('images/Canvas_moon.png', -3.5, -3.5)
    .restore()
    .restore()
    .arc(370,150,105, {
      border: '1px solid #FFF'
    })
    .image('images/Canvas_sun.png', 220, 0)
    .load(function(octx){
      octx.startRender(draw);
    })
}

draw();

Charts

To display data, the chart must be passed a data object that contains all of the information needed by the chart. The data object can contain different parameters.

Line

A line chart is a way of plotting data points on a line. Often, it is used to show trend data, and the comparison of two data sets.

octx.chartLine(config)
origami('canvas#chart-line')
  .chartLine({
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    fill: true,
    datasets: [
      {
        data: [1, 9, 8, 71, 56, 30, 60],
        line: "2px solid pink",
      },
      {
        data: [21, 29, 30, 25, 43, 50, 80],
        points: true,
        pointsColor: "purple",
        line: "4px dotted purple",
      },
      {
        data: [85, 40, 20, 10, 15, 18, 0],
        line: "1px dashed orange",
      }
    ]
  }).draw();

The following options can be included in chartLine dataset to configure options for that specific dataset.

Property Type Description
labels Array The label for the dataset which appears in the legend and tooltips
datasets Array Arrays of data objects. Example:
data: [], // array of numbers || array of arrays
points: true, //default: false
pointsColor: "green", //default: null
line: "1px dotted green" //default: "1px solid #000"
fill Boolean If true, fill the area under the line
animation String

The chart animation. Options: fade
Suggest an animation

gridLines Object Chart grid line configurations. Example:
vertical: true, //default: true
horizontal: false //default: true
labelColor String The Labels colors, default is #5e5e5e
gridLinesColor String The Grid Line colors, default is #e7e7e7
tense Number The Label Tense, default is 7