Creating canvas

Just as with regular JS, the basic concept of c0deff is canvas. Think of canvas as of virtual "scene" where everything is happening.

c0deff creates and manages the <canvas> elements for you, you have to just pass the target element, to which the canvas will be appended

It is pretty easy to create a new canvas:

var mycanvas = new cdf.Canvas(320, 140, "main");

The code above creates new canvas inside the element that has id of "core_01".

Of course, you can access the canvas in future using that variable:

mycanvas.fill('#c0deff');
mycanvas.text('Hello, C0deff!');

Virtual canvas

Third argument of canvas constructor (cdf.Canvas) is the element the canvas should be assigned to. You can pass an element id or the element itself (simply an html node element).

If the third argument was not provided - the canvas will only be created in memory, not assigned to anything and invisible. It still has all the features available. Also it can be attached to an element in future.

cdf.init

There's a function called cdf.init, that accepts a function as an argument. It may be useful to run code as soon as page finishes loading (similar to DOMContentLoaded event handler or JQuery's $ function)

This function receives an instance of cdf variable as its first argument and an instance of cdf.animate function.

cdf.init(function($, animate){
  $.Canvas(640, 480, 'main').setFit(true, true, true);
});

cdf.animate (callback)

cdf.animate allows you to run a piece of code every time animation frame is freed (plus it has a setTimeout fallback just in case):

cdf.init(function($, animate){
  var canvas = new $.Canvas(60,16, 'core_02');
  animate(function (frame) {
    canvas.clear().text((new Date).getSeconds(),0,0,'#000');
  });
});

In this example, the canvas is cleared every frame, and then current time seconds are placed onto it. If we did not cleared the canvas every time the text would layer one onto another.

cdf.animate(callback, repeats, every_real_frame_callback);

Sometimes you need faster/smoother animation. The cdf.animate function also supports optional second parameter for number of repeats per frame and optional third parameter for an additional function, that will be called every frame regardless of repeats number.

Here's a little example of using second and third parameters of that function:

cdf.init(function($, animate){

  var canvas = new $.Canvas(320,240, 'main');

  animate(

    function (frame) {
      var x = Math.sin(frame/50)*canvas.cx/2+canvas.cx;
      var y = Math.sin(frame/120)*canvas.cy/2+canvas.cy;
      canvas.plot( x, y, 1, '#fff');
    },

    10,

    function () {
      canvas.fill('rgba(0,0,0,0.2)');
    }
  )
});