/origami.js

HTML5 Canvas for Humans | 人間のためのキャンバス

Primary LanguageJavaScript

Origami Logo

HTML5 Canvas for Humans

Coverage Status Build Status Join the chat at https://gitter.im/raphamorim/origami.js

Initially it's a tool for teaching geometry, web and javascript in schools. Currently it's a powerful library to create using HTML5 Canvas

Summary

Why?

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.

Getting

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

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>

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();

axis

Based on Canvas Percentage

origami('.rect')
  .image('images/raphamorim.png', '5%', '5%', 200, 200)
  .load(function(canvas) {
    canvas.draw();
  });

percentage

Usage

draw

Method that performs the operation of drawing. If you forget to use, nothing will happen :)

origami('#canvas')
  .arc(100, 75, 50, {
    background: '#2A80B9',
    borderSize: '4px',
    borderColor: 'gold',
    borderStyle: 'dotted' })
  .draw();

arc

rect

origami('.canvas')
  .rect(10, 10, 50, 100, {
    background: 'lightblue',
    border: '4px solid #999'
  })
  .rect(50, 10, 40, {
    background: 'lightgreen',
    border: '10px solid green'
  })
  .draw();
Result:

rect

line

origami('.one')
  .line({x: 10, y: 10}, {x: 150, y: 200},
    {border: '1px dashed #888'})
  .draw();
Result:

line

arc

var style = {
  background: '#2A80B9',
  border: '4px dotted gold'
}

origami('.element')
  .arc(100, 75, 50, style)
  .draw();
Result:

arc

polygon

origami('.one')
  .polygon({x: 100, y: 110}, {x: 200, y: 10}, {x: 300, y: 110}, {
    background: '#2A80B9' })
  .draw();
Result:

polygon

border

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

border

shape (experimental feature yet)

CSS properties:

.pac-man {
  width: 0px;
  height: 0px;
  border-right: 60px solid transparent;
  border-top: 60px solid red;
  border-bottom: 60px solid red;
  border-left: 60px solid red;
  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();
Result:

text

text

origami('.one')
  .text("Nice!", 100, 100, {
    color: '#000',
    font: '70px Helvetica',
    align: 'center',
    border: '2px solid gold'
  })
  .draw()
Result:

text

image

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

// OR

origami('.canvas').image('images/dog.jpg', 10, 10)

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

origami('.one').clear()

background

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

getContexts

console.log(origami.getContexts()); // Array of all Origami contexts

canvasCtx

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

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

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

composition

Alias to globalCompositeOperation

Default: source-over

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

translate

Additional Options:

  • center (apply in canvas center)
  • reset (apply in 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: horizontal, vertical

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();
  })
Original Image

Person

Result

Person

rotate

Default: slow Options: slow, normal, fast

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

restore

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

save

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

src: required

speed: optional

loop: optional (default: true)

origami('#demo-1')
  .canvasBackground('#2A80B9')
  .sprite(40, 30, {
    src: 'images/coin-sprite.png',
    frames: 10,
    speed: 60,
    loop: true
  })
Result:

Sprite Example

nextFrame

Causes execution of a callback (through requestAnimationFrame)

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

stopFrame

Stop frame animation

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

First Example:

var rotation = 0;
function draw() {
    rotation = rotation + 0.1;
    origami('#demo-1')
        .clear()
        .arc(150, 150, 100)
        .save()
        .translate(150, 150)
        .rotate(rotation)
        .arc(18, 50, 5, {
            background: 'darkred'})
        .restore()
        .nextFrame(draw) }
Result:

Circle Rotate

Second Example:

Rewrite example of MDN on translation and rotation using origami.js

Original Code:

var sun = new Image();
var earth = new Image();
function init(){
  sun.src = 'https://mdn.mozillademos.org/files/1456/Canvas_sun.png';
  earth.src = 'https://mdn.mozillademos.org/files/1429/Canvas_earth.png';
  window.requestAnimationFrame(draw);
}

function draw() {
  var canvas = document.getElementById('canvas'),
      ctx = canvas.getContext('2d');

  ctx.globalCompositeOperation = 'destination-over';
  ctx.clearRect(0,0,300,300); // clear canvas

  ctx.fillStyle = 'rgba(0,0,0,0.4)';
  ctx.strokeStyle = 'rgba(0,153,255,0.4)';
  ctx.save();
  ctx.translate(150,150);

  // Earth
  var time = new Date();
  ctx.rotate( ((2*Math.PI)/60)*time.getSeconds() + ((2*Math.PI)/60000)*time.getMilliseconds() );
  ctx.translate(105,0);
  ctx.fillRect(0,-12,50,24); // Shadow
  ctx.drawImage(earth,-12,-12);

  ctx.restore();

  ctx.beginPath();
  ctx.arc(150,150,105,0,Math.PI*2,false); // Earth orbit
  ctx.stroke();
  ctx.drawImage(sun,0,0,300,300);
  window.requestAnimationFrame(draw);
}

init();

Rewritten Code with origami.js:

function draw() {
  origami('#canvas')
    .composition('destination-over')
    .clear()
    .save()
    .translate(150,150)
    .rotate('slow')
    .translate(105,0)
    .image('images/Canvas_earth.png', -12, -12)
    .restore()
    .arc(150,150,105, {
      border: '1px solid #FFF'
    })
    .image('images/Canvas_sun.png')
    .load(function(canvas){
      canvas.draw()
      canvas.nextFrame(draw)
    })
}
Result:

Earth Rotate

Browser Support

Chrome logo Firefox logo Internet Explorer logo Opera logo Safari logo
23+ ✔ 27+ ✔ 9+ ✔ 10.1+ ✔ 4+ ✔

Next Releases

  • bring acessibility to canvas
  • .hover, .click -> fn to current object
  • Improve style and shape (add more features)
  • .element (draw a entire element in canvas)
  • quadraticCurveTo
  • centerOf
  • animation based on CSS
  • own create gradient to use
  • render with textures
  • switch to WebGL
  • cube (3d)
  • cone (3d)
  • cylinder (3d)

Suggestions: interpolation D3 (animation) tween

Contributing

Want to contribute? Follow these recommendations.

License

CC0