HTML5 canvas Spline 教程

要使用 Konva 创建样条曲线,我们可以实例化一个带有 tension 属性的 Konva.Line() 对象。

要定义线条的路径,应使用 points 属性。如果你有三个点的 xy 坐标,你应该将 points 属性定义为:[x1, y1, x2, y2, x3, y3]

扁平的数字数组的性能应该比对象数组更快,并且占用更少的内存。

有关属性和方法的完整列表,请查看 Konva.Line 文档

Konva Spline 示例view raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/konva@9.3.18/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Line Spline Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;

var stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
});

var layer = new Konva.Layer();

var redLine = new Konva.Line({
points: [5, 70, 140, 23, 250, 60, 300, 20],
stroke: 'red',
strokeWidth: 15,
lineCap: 'round',
lineJoin: 'round',
tension: 1,
});

// dashed line
var greenLine = new Konva.Line({
points: [5, 70, 140, 23, 250, 60, 300, 20],
stroke: 'green',
strokeWidth: 2,
lineJoin: 'round',
/*
* line segments with a length of 33px
* with a gap of 10px
*/
dash: [33, 10],
lineCap: 'round',
tension: 0.5,
});

// complex dashed and dotted line
var blueLine = new Konva.Line({
points: [5, 70, 140, 23, 250, 60, 300, 20],
stroke: 'blue',
strokeWidth: 10,
lineCap: 'round',
lineJoin: 'round',
/*
* line segments with a length of 29px with a gap
* of 20px followed by a line segment of 0.001px (a dot)
* followed by a gap of 20px
*/
dash: [29, 20, 0.001, 20],
tension: 0.7,
});

/*
* since each line has the same point array, we can
* adjust the position of each one using the
* move() method
*/
redLine.move({
x: 20,
y: 5,
});
greenLine.move({
x: 20,
y: 55,
});
blueLine.move({
x: 20,
y: 105,
});

layer.add(redLine);
layer.add(greenLine);
layer.add(blueLine);

// add the layer to the stage
stage.add(layer);
</script>
</body>
</html>