二维绘图引擎ZRender

1、开始使用
描述
ZRender是二维绘图引擎,它提供 Canvas、SVG、VML 等多种渲染方式。ZRender 也是 ECharts 的渲染器。
下载
ZRender 项目在 gitHub ,也可以使用 npm install zrender 下载。
在 dist 目录下找到 zrender.js 和 zrender.min.js,前者是开发版,后者是发布版。
初始化 ZRender
在使用 ZRender 前需要初始化实例,具体方式是传入一个 DOM 容器:

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

创建出的这个实例对应文档中 zrender 实例部分的方法和属性。
在场景中添加元素
ZRender 提供了将近 20 种图形类型,可以在文档 zrender.Displayable 下找到。如果想创建其他图形,也可以通过 zrender.Path.extend 进行扩展。
以创建一个圆为例:

//圆
var circle = new zrender.Circle({
    shape: {
        cx: 150,
        cy: 50,
        r: 40
    },
    style: {
        fill: 'none',
        stroke: '#F00'
    }
});
zr.add(circle);

//圆弧
var arc=new zrender.Arc({
            style:{
                stroke:'none',
                fill:'red'
            },
            shape:{
                cx:300,
                cy:300,
                r:140,
                startAngle:0,              //开始角度
                endAngle:Math.PI/3         //结束角度
            }
        });
        zr.add(arc);
        
		//扇形
        var sector=new zrender.Sector({
            style:{
                fill:'red'
            },
            shape:{
                cx:300,
                cy:300,
                r:80,                     //外半径
                r0:0,                    //内半径
                startAngle:0,             //开始角度
                endAngle:Math.PI/3,       //结束角度
                clockwise:true            //顺时针
            }
        });
        zr.add(sector);
 //椭圆
        var ellipse=new zrender.Ellipse({
            style:{
                fill:'red'
            },
            shape:{
                cx:200,
                cy:200,
                rx:80,         //横向半径
                ry:40           //纵向半径
            }
        })
        zr.add(ellipse);
 //心型
        var heart =new zrender.Heart({
            style:{
                fill:'red'
            },
            shape:{
                cx:200,
                cy:200,
                width:80,
                height:100
            }
        });
        zr.add(heart);
        //多边形
        var Polygon=new zrender.Polygon({
            style:{
                fill:'red'
            },
            shape:{
                points:[[100,100],[200,80],[300,160],[150,130],[20,300]]    //坐标集合
            }
        })
        zr.add(Polygon)

创建了一个圆心在 [150, 50] 位置,半径为 40 像素的圆,并将其添加到画布中。
修改图形元素属性
通过 a = new zrender.XXX 方法创建了图形元素之后,可以用 a.shape 等形式获取到创建时输入的属性,但是如果需要对其进行修改,应该使用 a.attr(key, value) 的形式修改,否则不会触发图形的重绘。例子:

var circle = new zrender.Circle({
    shape: {
        cx: 150,
        cy: 50,
        r: 40
    }
});
zr.add(circle);
console.log(circle.shape.r); // 40
circle.attr('shape', {
    r: 50 // 只更新 r。cx、cy 将保持不变。
});

图形里的文字
text:'图形文字', //文字
textFill:'#333', //文字颜色
fontSize:12, //文字大小
fontFamily:'', //字体
fontStyle:'normal', //字形
fontWeight:'normal', //加粗
textStroke:'yellow', //文字描边
textWidth:1, //字体线宽
textHeight:12, //字体高度
textLineWidth:1, //字体描边线宽
textLineHeight:14, //字体行高
textPosition:'inside', //字体位置
textPadding:[0,0,0,0], //文字内边距
transformText:true //字体跟随变换效果

//图形里的文字
        circle.attr({
            style:{
                text:'江西理工大学',   //文字
                textFill:'yellow',   //文字颜色
                fontSize:10,    //文字大小
                textPosition:'inside',    //字体位置
                textPadding:[3,3,3,3],    //文字内边距
                // transformText:true    //字体跟随变换效果
            }
        })

如何给图形添加事件响应?
ZRender支持的事件有: ‘click’、 ‘mousedown’、 ‘mouseup’、 ‘mousewheel’、 ‘dblclick’、 ‘contextmenu’。

//添加事件
        rect.on('click',function(e){
           alert('点击了矩形')
        })

完整代码:
在这里插入图片描述

<template>
    <div id="zrCircle">

    </div>
</template>
<script>
import zrender from 'zrender'
export default {
    mounted(){
        //初始化zrender
        var zr=zrender.init(document.getElementById("zrCircle"),{
            renderer:'canvas',   //渲染方式
            width:'600',     //画布宽度
            height:'600'     //画布高度
        });
        // opts.height=600
        //在场景中添加元素,一个半径为40的圆
        var circle=new zrender.Circle({
            shape:{
                cx:150,   
                cy:150,
                r:40
            },
            style:{
                fill:'none',     //圆背景色不设置,即白色
                stroke:'blue'    //圆的边框颜色
            }
        });
        //图形里的文字
        circle.attr({
            style:{
                text:'江西理工大学',   //文字
                textFill:'yellow',   //文字颜色
                fontSize:10,    //文字大小
                textPosition:'inside',    //字体位置
                textPadding:[3,3,3,3],    //文字内边距
                // transformText:true    //字体跟随变换效果
            }
        })
        //向画布中添加已经定义图形
        zr.add(circle); 
        //修改图形元素属性   
        console.log('更新后:',circle.shape.r); // 40
        circle.attr('shape', {    //改变shape中的属性
            r: 50             // 只更新 r。cx、cy 将保持不变。
        });
        console.log('更新前:',circle.shape.r); // 40
        circle.attr('style',{     //改变style中的属性
            fill:'skyblue'
        })
    }
}
</script>

2、动画
给图形添加动画支持
animate函数 animate(path, loop):
path 对该对象的哪个元素执行动画
loop 为boolean类型,表示是否循环动画

 //给图形添加动画
        circle.animate('shape',true)
                .when(1000,{cx:200,r:30})
                .when(2000,{cx:250,r:20})
                .when(3000,{cx:300,r:30})
                .when(4000,{cx:350,r:40})
                .start();   //表示动画开始执行
        circle.animate('style',true)
                .when(1000,{opacity:0.8})
                .when(2000,{opacity:0.5})
                .when(3000,{opacity:0.3})
                .when(4000,{opacity:0.6})
                .when(4000,{opacity:0.9})
                .start();

animateTo 函数
animateTo(target, time, delay, easing, callback, forceAnimate):为属性设置动画。
部分参数可缺省,支持以下形式的调用:

animateTo(target, time, delay, easing, callback, forceAnimate)   //属性,时长,延迟,缓动函数。回调函数,相同属性是否强制执行
animateTo(target, time, delay, easing, callback)
animateTo(target, time, easing, callback)
animateTo(target, time, delay, callback)
animateTo(target, time, callback)
animateTo(target, callback)
animateTo(target)

参数
target 设置动画的对象
time 动画时长
delay 动画延迟执行的时长
easing 缓动函数名称
callback 动画执行完成后的回调函数
forceAnimate 对于相同的属性,是否强制执行

//将圆的半径缓慢的增加至100,颜色改变为红色
        circle.animateTo({
            shape:{
                r:100
            },
            style:{
                fill:'red'
            },
            position:[10,10]    //x,y轴分别平移10
        },3000,100,'cubicOut',function(){
            console.log('done')
        });

旋转,放大,缩小,平移

//旋转,放大,缩小,平移
 rect.animateTo({
       // rotation:Math.PI/3,     //正值代表逆时针旋转,负值代表顺时针旋转
       rotation:Math.PI,
       origin:[240,190],
       scale:[1.5,1.5],   //x,y轴方向放大至1.5倍
       position:[100,100]    //x,y轴分别平移100
   })

在这里插入图片描述
stopAnimation(forwardToLast)函数
.stopAnimation(Boolean) 是否将动画跳到最后一帧。 true为跳到最后,false为不跳,设置了该函数,不论Boolean为什么,动画停止

circle.stopAnimation(true);    //跳到动画最后一帧

animate函数 动画对象
delay(time) 延迟开始时间
done(callback) 设置动画结束的回调函数
during(callback) 为关键帧添加回调函数,在关键帧运行后执行
isPaused() 获得动画是否处于暂停状态。Boolean类型
pause() 暂停动画
resume() 恢复动画
start(easing) 执行动画(缓动函数)
stop(forwardToLast) 停止动画(boolean,是否将动画跳到最后一帧)
when(time,props) 定义关键帧,即动画对象在某个时刻的属性。

3、组的概念
组。Group 是一个容器,可以插入子节点,Group 的变换也会被应用到子节点上。

 //getBoundingRect() 获取元素包围盒
        var g=new zrender.Group({
            slient:true                   //组内子孙元素是否响应鼠标事件
        });
        var rect=new zrender.Rect({
            style:{
                fill:'blue'
            },
            shape:{
                x:10,
                y:10,
                width:50,
                height:40
            }
        });
        var circle=new zrender.Circle({
            style:{
                fill:'blue'
            },
            shape:{
                cx:200,
                cy:50,
                r:30
            }
        });
        g.add(rect);   //添加子节点
        g.add(circle);
        zr.add(g);

        //.getBoundingRect()得到组内所有元素的包围盒
        console.log(g.getBoundingRect());
        //返回所有子元素,类型:Element[]。
        console.log('cc',g.children());
        //返回特定名字的子元素
        console.log('circle',g.childOfName('circle'));
        //返回子元素个数
        console.log('num',g.childCount());


        //遍历所有子节点
        g.eachChild(function(item){ 
            console.log('a',item);
        })    

        //在组内删除元素
        // g.remove(circle)   //指定删除
        // g.removeAll()      //清空组内所有元素

        //整体变换,如
        g.attr({
            position:[100,100],       //x轴,y轴分别平移100
        })      

4、线

 //直线
        var line =new zrender.Line({
            style:{
                stroke:'red',       //线的颜色
                lineWidth:3,        //线宽
                lineDash:[0]        //虚线样式
            },
            shape:{
                x1:30,              //起始点横坐标
                y1:30,              //起始点纵坐标
                x2:100,             //结束点横坐标
                y2:100,             //结束点横坐标
                percent:1         //已显示的百分比,用于绘制动画。
            }
        });
        zr.add(line);
        //多边形折线段
        var polyline=new zrender.Polyline({
            style:{
                stroke:'blue',       //线的颜色
                lineWidth:1,        //线宽
                lineDash:[0] 
            },
            shape:{
                points:[[10,20],[100,120],[100,200]]     //点集
            }
        })
        zr.add(polyline)
        //贝塞尔曲线
        var bezierCurve=new zrender.BezierCurve({
            style:{
                stroke:'yellow',
                lineWidth:3
            },
            shape:{
                x1:70,            //起始点横坐标
                y1:10,            //起始点纵坐标
                x2:150,           //结束点横坐标
                y2:150,           //结束点横坐标
                cpx1:60,           //控制点横坐标
                cpy1:50            //控制点纵坐标
            }
        });
        zr.add(bezierCurve)

在这里插入图片描述
5、文字

 //初始化zrender
        var zr=zrender.init(document.getElementById("zrCircle"),{
            renderer:'canvas',   //渲染方式
            width:'600',     //画布宽度
            height:'600'     //画布高度
        });

        var text=new zrender.Text({
            style:{
                text:'这是一段文字'+'\n'+'换行',
                textPadding:[3,5,3,5],
                fontSize:16
            }
        });
        zr.add(text);
        //可以通过getBoundingRect()获取文字所占的空间
        console.log('文字所占空间',text.getBoundingRect());

        //特别注意的是rect必须设置宽高,才能获取到其所占的空间
        var rect=new zrender.Rect({
            style:{
                text:'这是文字',
                fontSize:16,
                textFill:'skyblue'   //字体颜色
            },
            shape:{
                x:150,
                y:150
            }
        })
        zr.add(rect);
        console.log(rect.getBoundingRect())
        //返回{x: 10, y: 10, width: 0, height: 0}

        //文字包围盒
        var text=new zrender.Text({
            style:{
                text:'这是一段文字',
                textBackgroundColor:'red',     //包围盒背景
                textBorderColor:'#ccc',         //包围盒描边颜色
                textBorderWidth:1,             //包围盒描边线宽
                textPadding:[10,20,10,20]      //文字内边距,同css Padding
            }
        });

在这里插入图片描述
6、线性渐变
zrender.LinearGradient(x, y, x2, y2, colorStops, globalCoord) 起始横坐标,起始纵坐标,结束横坐标,结束纵坐标,组成渐变色的颜色,取值范围

//线性渐变
        var linearColor = new zrender.LinearGradient(0, 0, 0, 1, [
            {
                offset: 0,      
                color: '#efe3ff'
            },
            {
                offset: 1,
                color: '#6cb3e9'
            }
        ]);
        var rect = new zrender.Rect({
            shape: {
                x: 0,    
                y: 0,    
                width: 100,     
                height:100
            },
            style: {
                fill:linearColor
            },
            position: [10,10]
        
        });
        zr.add(rect );

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值