可视化图表(1)-zrender使用

5,771 阅读2分钟

介绍

zrender是一种开源二维绘图引擎,可用来绘制图表、图形等内容

安装

  1. 页面引入
    <script src="./zrender.js"></script>
  1. npm引入
    npm install zrender

初始化

需要传入对应dom对象,实例化zrender

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

图形、组添加

    //添加分组
    var group = new zrender.Group();
    zr.add(group);
    //添加图形
    var rect = new zrender.Rect({
        shape:{
            x:0,
            y:0,
            width:100,
            height:100
        }
    });
    group.add(rect)

图形库

zrender封装了常用的图形,可以直接通过new zrender.xxx({})调用;并且开放了自定义图形方法,通过zrender.path.extend拓展自己需要的图形。

支持图形

  • Arc 实心圆、半圆
  • BezierCurve 贝塞尔曲线
  • Circle 实心圆、圆环
  • Image图片
  • Isogon正多边形
  • Line直线
  • Polygon多边形区域
  • Polyline多折线
  • Rect矩形
  • Sector扇形、空心扇形
  • Text文字

图形的使用

  • 实例化
    var rect = new zrender.Rect({
        shape:{
            x:0,
            y:0,
            width:100,
            height:100
        }
    });
  • 自定义图形

通过继承自zrender的path,实现自定义图形的绘制

    var triangleSelf = zrender.Path.extend({
    	type: 'triangleSelf',
    	shape: {
    	    x: 0,
    	    y: 0,
    	    width: 0,
    	    height: 0
    	},
    	buildPath: function (ctx, shape) {
            var x = shape.x;
            var y = shape.y;
            var height = shape.height;
            var width = shape.width;
            ctx.moveTo(x,y);
            ctx.lineTo(x+width/2,y+height);
            ctx.lineTo(x-width/2,y+height);
            ctx.closePath();
    	}
    })
    //使用
    var sf = new triangleSelf({
    	shape: {
             x: 200,
            y: 0,
            width: 100,
            height: 100
    	}
    })

事件

通过el.on()绑定事件,el.off()取消绑定事件;group也可绑定事件,触发分组内具体对象才会触发

  • 支持事件

'click'、 'mousedown'、 'mouseup'、 'mousewheel'、 'dblclick'、 'contextmenu'

动画

动画主要分成两种animateanimateToanimate可以监测动画执行,可以在during中控制其他相关联动和一些处理,并可以对某些属性设定循环

animateTo

el.animateTo(target, time, delay, easing, callback, forceAnimate)

名称 类型 默认值 描述
target Object -- zrender图形对象
time number 500 动画时长,单位毫秒
delay number 0 动画延迟执行的时长,单位毫秒
easing string 'linear' 缓动函数名称,支持的名称参见缓动函数
callback Function -- 动画执行完成后的回调函数
forceAnimate boolean false 对于相同的属性,是否强制执行
el.animateTo({
    shape: {
        width: 500
    },
    style: {
        fill: 'red'
    }
    position: [10, 10]
}, 100, 100, 'cubicOut', function () {
    // done
});

animate

el.animate('style', false)
    .when(1000, {x: 10})
    .delay(100),
    .done(function () {
         // Animation done
    }),
    during(function(){
        
    })
    .start()

更新

  • 属性更新

实例化的图形对象采用ele.shape.x=100的方式修改不会触发重绘,推荐调用el.attr方法触发

  • 组、zrender实例更新

对于组或者整个zrender对象重绘调用dirty()方法触发

对象的销毁

离开页面或者组件不使用时及时销毁,节约内存开销

    //zr为init的zrender对象
    zrender.dispose(zr)