Why GraphicsJS

There are many SVG libraries to choose from for the front end, such as Snap.svg or BonsaiJS, but each has its own advantages. This article is mainly about GraphicsJS to let you know its advantages and characteristics.

  • Lightweight, flexible Javascript API

  • From AnyChart team, a very famous visualization team in the world.

  • GraphicsJS is an open source project that does not require a commercial license

  • IE6 is supported for older browsers

  • Good support for graphics and animations to help developers create complex interactions

Basic use of GraphicsJS

<style>  
.stage{
  width: 280px;
  height: 280px;
}
</style>

<div class="stage" id="rect1"></div>

 <script src="https://cdn.anychart.com/js/latest/graphics.min.js"></script>


<script>  
 // create a stage
  var stage = acgraph.create('rect1');
  // draw a rectangle
  stage.rect(25, 50, 200, 200);
</script>  
...
Copy the code

`

Go further

Fill, Stroke and pattern fill

You can use fill and stroke to change the color properties for any shape or path, but you can only use fill for closures and paths or shapes, and you can also fill with gradients and images. And GraphicsJS also allows you to define your own filled patterns. Let’s implement a more complex effect where a person is next to a house (see Sitepoints) :

// create a label to count leaves
var counterLabel = stage.text(10,10, "Swiped: 0", {fontSize: 20});

// a layer for the leaves
var gameLayer = stage.layer().zIndex(counterLabel.zIndex()-1);
Copy the code

Now let’s color up the graph.

function drawLeaf(x, y) {  
  // choose a random color from a palette
  var index = Math.floor(Math.random() * 5);
  var fill = palette_fill[index];
  var stroke = palette_stroke[index];

  // generate random scaling factor and rotation angle
  var scale = Math.round(Math.random() * 30) / 10 + 1;
  var angle = Math.round(Math.random() * 360 * 100) / 100;

  // create a new path (leaf)
  var path = acgraph.path();

  // color and draw a leaf
  path.fill(fill).stroke(stroke, 1, 'none', 'round', 'round');
  var size = 18;
  path.moveTo(x, y)
    .curveTo(x + size / 2, y - size / 2, x + 3 * size / 4, y + size / 4, x + size, y)
    .curveTo(x + 3 * size / 4, y + size / 3, x + size / 3, y + size / 3, x, y);

  // apply random transformations
  path.scale(scale, scale, x, y).rotate(angle, x, y);

  return path;
};
Copy the code

Now it looks like we have another person in a dress, standing next to the castle, and we can also fill the background of the box with copyright symbols, and we can use custom fill templates.

path.listen("mouseover", function(){  
  path.remove();
  counterLabel.text("Swiped: " + leavesCounter++);
  if (gameLayer.numChildren() < 200) shakeTree(300);
});
Copy the code

It is very easy to create a text and generate a fill pattern.

Effect of the Demo

Let’s create a simple interactive game

The game is very simple users through the mouse sweep leaves. When the mouse slides over the leaf, the leaf will disappear automatically.

Layers, zIndex and the Virtual DOM

First we create some initialization variables

function shakeTree(n){  
  stage.suspend(); // suspend rendering
  for (var i = 0; i < n; i++) {
    var x = Math.random() * stage.width()/2 + 50;
    var y = Math.random() * stage.height()/2 + 50;
    gameLayer.addChild(drawLeaf(x, y)); // add a leaf
  }

  stage.resume(); // resume rendering
}
Copy the code

In the game we need to use Layer, which is an object with multiple primary colors, and these elements are best divided into groups so that we can operate in batches. In the Demo we need to put the leaves in a group to avoid covering up the odd number of text, so we also need to create a label and use stage.layer, so we put the leaves layer under it by setting zIndex.

// create a label to count leaves
var counterLabel = stage.text(10,10, "Swiped: 0", {fontSize: 20});

// a layer for the leaves
var gameLayer = stage.layer().zIndex(counterLabel.zIndex()-1);
Copy the code
function drawLeaf(x, y) {  
  // choose a random color from a palette
  var index = Math.floor(Math.random() * 5);
  var fill = palette_fill[index];
  var stroke = palette_stroke[index];

  // generate random scaling factor and rotation angle
  var scale = Math.round(Math.random() * 30) / 10 + 1;
  var angle = Math.round(Math.random() * 360 * 100) / 100;

  // create a new path (leaf)
  var path = acgraph.path();

  // color and draw a leaf
  path.fill(fill).stroke(stroke, 1, 'none', 'round', 'round');
  var size = 18;
  path.moveTo(x, y)
    .curveTo(x + size / 2, y - size / 2, x + 3 * size / 4, y + size / 4, x + size, y)
    .curveTo(x + 3 * size / 4, y + size / 3, x + size / 3, y + size / 3, x, y);

  // apply random transformations
  path.scale(scale, scale, x, y).rotate(angle, x, y);

  return path;
};
Copy the code

Add Event Handling

Any object layer in GraphicsJS can handle events, and here you can see the supported event types. Here we also need to bind the leaf to the mouse over event, and the leaf performs the function when the mouse moves over it.

path.listen("mouseover", function(){  
  path.remove();
  counterLabel.text("Swiped: " + leavesCounter++);
  if (gameLayer.numChildren() < 200) shakeTree(300);
});
Copy the code

To optimize the

The virtual DOM of binding events allows developers to control rendering themselves, and for performance optimization tips, see here.

In order for us to see the effect over time, we need to add some leaves as the number of leaves decreases.

function shakeTree(n){  
  stage.suspend(); // suspend rendering
  for (var i = 0; i < n; i++) {
    var x = Math.random() * stage.width()/2 + 50;
    var y = Math.random() * stage.height()/2 + 50;
    gameLayer.addChild(drawLeaf(x, y)); // add a leaf
  }

  stage.resume(); // resume rendering
}
Copy the code

The purpose of this letter is to keep adding new leaves.

The effect is as follows:

Effect of the DEMO

summary

With H5 turning the Web upside down and the need for graphics on its head, try graph.js as an open source project. It’s small and powerful, with enough apis to support your work, and you don’t have to worry about browser compatibility. There are plenty of demos available for you to study and learn on your own.