Konva 使用方法
1. 创建舞台 new Konva.Stage()
注:初始化 Konva 时需要调用 Konva.Stage 构造函数
const stage = new Konva.Stage({
container: 'dom元素',
width: 600,
height: 800,
draggable: true // 是否舞台可拖动
})
2. 创建背景区域
注:添加了 layer,Dom才会创建对应的layre canvas元素
const layer = new Konva.Layer({
nane: 'background',
// 默认居中布局
x: stage.width() / 2 - width / 2,
y: stage.height() / 2 - height / 2,
})
3. 图层shape (常见的有)
组 (Group)
const group = new Konva.Group({
x: 120,
y: 40,
draggable: true,
rotation: 20
});
矩形(Rect)
const rect = new Konva.Rect({
x: 0,
y: 0,
width: 300,
height: 300,
fill: '#ff5645',
stroke: '#000'
});
圆形(Circle)
const circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 40,
fill: 'red',
})
圆环(Ring)
const ring = new Konva.Ring({
x: stage.width() / 2,
y: stage.height() / 2,
innerRadius: 40,
outerRadius: 70,
fill: 'yellow',
stroke: 'black',
strokeWidth: 4
});
椭圆(Ellipse)
const ellipse = new Konva.Ellipse({
x: 100,
y: 100,
radius: {
x: 70,
y: 40,
},
fill: '#888'
)}
线条(Line) 可以利用线条完成多边形
const line = new Konva.Line({
points: [x1, y1, x2, y2, x3, y3],
stroke: 'blue',
strokeWidth: 1,
lineCap: 'round',// 线条两端的样式 butt\ round\square
lineJoin: 'round', // 两条线连接点的过渡样式 bevel\ round\miter
// closed: true, 头尾相连
// tension: 0.3, 让线条光滑化
// dash: [3, 3] 虚线
});
图片(Image)
const originImg = new Image();
originImg.src = './fe_watermelon.png';
originImg.onload = () => {
// 绘制图片
const img = new Konva.Image({
x: 30,
y: 30,
image: originImg
});
扇形(Wedge)
const wedge = new Konva.Wedge({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 70,
angle: 60,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
rotation: -120
});
文字(Text)
const text = new Konva.Text({
x: 0,
y: 0,
fontSize: 18,
text: 'sssssssss',
width: 110,
align: 'center',
fontFamily: 'Songti SC', // 宋体
ellipsis: true,
fill: 'black',
verticalAlign: 'middle'
});