ZRender Tutorial for Creating Stunning Web Graphics and Visualizations

Introduction to ZRender

ZRender is a powerful and extensible library for creating complex and scalable visualizations on the web. Built on top of HTML5 Canvas, it allows developers to craft intricate graphics, animations, and interactions with ease. In this article, we’ll explore some of the most useful API methods of ZRender alongside code snippets to demonstrate their functionality.

Basic Setup

First, include the ZRender library in your HTML file:

  <script src="https://cdn.jsdelivr.net/npm/zrender@4.4.4/dist/zrender.min.js"></script> 

Creating the ZRender Instance

Initialize a ZRender instance:

  var zr = zrender.init(document.getElementById('main')); 

Drawing Basic Shapes

Creating a Rectangle:

  var rect = new zrender.Rect({
  shape: {
    x: 50,
    y: 50,
    width: 100,
    height: 50
  },
  style: {
    fill: 'blue'
  }
}); zr.add(rect); 

Creating a Circle:

  var circle = new zrender.Circle({
  shape: {
    cx: 200,
    cy: 150,
    r: 50
  },
  style: {
    fill: 'red'
  }
}); zr.add(circle); 

Creating Complex Shapes

Creating a Polygon:

  var polygon = new zrender.Polygon({
  shape: {
    points: [[0, 0], [100, 0], [50, 80]]
  },
  style: {
    fill: 'yellow'
  }
}); zr.add(polygon); 

Animation and Interaction

Animating Shapes:

  rect.animate('shape', true)
   .when(2000, {
     x: 200,
     y: 200
   })
   .start();

Handling Events:

  circle.on('click', function () {
  alert('Circle clicked!');
}); 

Building a Simple App

Combining the above methods, let’s create a simple app:

  <html> <head>
  <script src="https://cdn.jsdelivr.net/npm/zrender@4.4.4/dist/zrender.min.js"></script>
</head> <body>
  <div id="main" style="width: 500px; height: 500px;"></div>
  <script>
    var zr = zrender.init(document.getElementById('main'));

    var rect = new zrender.Rect({
      shape: {
        x: 50,
        y: 50,
        width: 100,
        height: 50
      },
      style: {
        fill: 'blue'
      }
    });
    zr.add(rect);

    var circle = new zrender.Circle({
      shape: {
        cx: 200,
        cy: 150,
        r: 50
      },
      style: {
        fill: 'red'
      }
    });
    zr.add(circle);

    rect.animate('shape', true)
       .when(2000, {
         x: 200,
         y: 200
       })
       .start();

    circle.on('click', function () {
      alert('Circle clicked!');
    });
  </script>
</body> </html> 

By leveraging the capabilities of ZRender, you can craft highly interactive and visually appealing web applications with minimal effort. Experiment with different shapes, styles, and interactions to create unique graphics for your projects.


Hash: 747a2c8515b2bd4099b73102966794497f7be31c0608b40065c5c14fe4ff1de7

Leave a Reply

Your email address will not be published. Required fields are marked *