Konva-前端绘图框架,轻松进行分层绘制


一、介绍

Konva is an HTML5 Canvas JavaScript framework that extends the 2d context by enabling canvas interactivity for desktop and mobile applications.
Konva enables high performance animations, transitions, node nesting, layering, filtering, caching, event handling for desktop
and mobile applications, and much more.
You can draw things onto the stage, add event listeners to them, move them, scale them, and rotate them independently from other shapes to support high performance animations, even if your application uses thousands of shapes.
This project began as a GitHub fork of KineticJS.

大白话翻译:
Konva是一个H5 Canvas的JavaScript的框架,它通过为桌面和移动应用程序启用画布交互来扩展2d上下文。
Konva为桌面应用和移动应用程序提供高性能动画,过渡,节点嵌套,分层,过滤,缓存,事件处理等。
你可以将事物绘制到Stage上,向其添加事件侦听器,使用高性能动画对其进行移动,缩放以及从其他形状中独立旋转它们,即使你的应用程序使用数千种形状。
这个项目开始于KineticJS的GitHub分支。

简单来说,Konva同fabricjs类似,是一个2d的canvas绘图框架框架。其以stage、layer、group的分层分组方式实现层级绘图,并以组件化的方式管理绘图,提供事件监听器和高性能动画。


二、官方地址

  1. Konva官方地址:https://konvajs.org/
  2. Konva的Github开源地址:https://github.com/konvajs/konva
  3. Api文档:https://konvajs.org/docs/index.html
  4. vue-konva:https://github.com/konvajs/vue-konva

三、使用方法

在某个vue项目中使用了konva,但是没有使用vue-konva。因为vue-konva使用的是标签形式创建各图像组件,因为绘制的图形有点稍稍复杂,可能使用标签的形式不是很方便,还是在外写好再import的方式。

3.1 开始使用

两种方式引用,一种是通过npm instsall的方式;

npm install konva

另一种是使用script标签。

<script src="https://unpkg.com/konva@7.0.3/konva.min.js"></script>

不同于其它框架,konva的id是绑定自一个div标签,而非canvas的id。当用stage绑定后会在该div下自行插入canvas标签。开始使用时需要创建一个stage,即承载各个层、组、图形的舞台;

<div id="container"> </div>
let stage = new Konva.Stage({
   
        container: 'container', //div的id
        width: width, //宽度
        height: height, //高度
      });

Konva提供了Rect、Circle、Ellipse、Wedge、Line、Sprite、Image、Text、TextPath、Star、Ring、Arc、Label、Path、RegularPolygon、Arrow、Custom等图形、图像和文字组件。基本每个图形的创建都是new Konva.Shape的方式,例如矩形:

let rect = new Konva.Rect({
   
		x: 30,
		y: 30,
		width: 150,
		height: 50,
		fill: 'red',
		stroke: 'black',
		strokeWidth: 2,
	});

添加完后需要往layer里添加,再把layer往stage里添加。但是一个stage里最好只有2-3层layer,因为一个每添加一个layer就会往绑定的div里插入一个canvas。加入canvas越多,渲染性能越差。同时控制台也会疯狂的弹警告。

Konva warning: The stage has x layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group.

正确的做法是引入group,group可以创建多个,将需要加入的图形往group添加,再将group往layer里添加。即一个stage添加最多3-5层layer,一层layer可以添加多个group,一个group又可以添加多个shape

  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值