一、单个使用
基础:使用konva,首先需要创建舞台也就是stage,然后创建一个Layer图层,将图层放到舞台上,将图形等内容放到图层上
// 引入konva.js
<script src="https://unpkg.com/konva@3.2.4/konva.min.js"></script>
// 第一步:创建一个Stage舞台
var stage = new Konva.Stage({
container: 'container',
width: window.innerWidth, // 舞台宽度
height: window.innerHeight // 舞台高度
});
// 第二步:创建一个Layer图层
var layer = new Konva.Layer();
// 第三步:创建一个Rect矩形
var rect = new Konva.Rect({
x: 100,
y: 100,
width: 100,
height: 50,
fill: 'green',
stroke: 'black',
strokeWidth: 4
});
// 第四步:将矩形添加到图层中
layer.add(rect);
// 第五步:将图层添加到舞台中
stage.add(layer);
1.矩形
var rect = new Konva.Rect({
x: 20,
y: 20,
width: 100,
height: 50,
fill: 'green',
stroke: 'black',
strokeWidth: 4
});
2.圆
var circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 70,
fill: 'red',
stroke: 'black',
strokeWidth: 4
});
3.椭圆
var ellipse= new Konva.Ellipse({
x: stage.width() / 2,
y: stage.height() / 2,
radiusX: 100,
radiusY: 50,
fill: 'yellow',
stroke: 'black',
strokeWidth: 4
});
4.线
var line = new Konva.Line({
points: [5, 70, 140, 23, 250, 60, 300, 20],
stroke: 'red',
strokeWidth: 15,
lineCap: 'round',
lineJoin: 'round'
});
5.图片
// 第一种
var imageObj = new Image();
imageObj.onload = function () {
var yoda = new Konva.Image({
x: 50,
y: 50,
image: imageObj,
width: 106,
height: 118,
});
layer.add(yoda);
};
imageObj.src = '/assets/yoda.jpg';
// 第二种
Konva.Image.fromURL('/assets/darth-vader.jpg', function (darthNode) {
darthNode.setAttrs({
x: 200,
y: 50,
scaleX: 0.5,
scaleY: 0.5,
});
layer.add(darthNode);
});
6.多边形
var poly = new Konva.Line({
points: [23, 20, 23, 160, 70, 93, 150, 109, 290, 139, 270, 93],
fill: '#00D2FF',
stroke: 'black',
strokeWidth: 5,
closed: true,
});
7.文字
var simpleText = new Konva.Text({
x: stage.width() / 2,
y: 15,
text: '文字',
fontSize: 30,
fontFamily: 'Calibri',
fill: 'green'
});
二、组合使用(group)
var stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight-130,
});
var layer = new Konva.Layer();
var groupItem = new Konva.Group({
draggable: false //是否能拖动
});
var circle = new Konva.Circle({
x: 0,
y: 0,
radius: 10,
fill: '#FFFFFF',
stroke: "#b8bfbf",
strokeWidth: 3,
});
var name = new Konva.Text({
x: 10,
y: 20,
text: "group name",
fontSize: 8,
fontFamily: "Calibri",
fill: "#000000",
padding: 10,
align: "center"
});
groupItem.add(circle);
groupItem.add(name);
layer.add(groupItem);
stage.add(layer);