www说
我们可以将所有曲线放入一个数组中,然后循环它们,在绘制下一条贝塞尔曲线之前移动到最后一个点。下面是示例代码:<canvas id="myCanvas" width="600" height="150"></canvas><script> var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); function drawCurve(x, y, curves) { context.beginPath(); context.moveTo(x, y); for (i = 0; i < curves.length; i++) { c = curves[i] context.bezierCurveTo(c[0], c[1], c[2], c[3], c[4], c[5]); context.moveTo(c[4], c[5]); context.stroke(); } } context.strokeStyle = 'blue'; drawCurve(0, 150, [ [100, 0, 200, 100, 300, 50], [400, 0, 500, 100, 600, 20] ]); context.strokeStyle = 'red'; drawCurve(0, 10, [ [100, 0, 180, 90, 280, 50], [400, 0, 400, 80, 600, 120] ]); context.strokeStyle = 'green'; drawCurve(0, 80, [ [100, 0, 90, 45, 140, 25], [200, 0, 200, 40, 300, 50], [500, 60, 400, 80, 300, 120], [300, 120, 200, 160, 100, 80], ]);</script>但“不平滑的线”也取决于你的曲线,如果它们的方向完全相反,我们会看到尖锐的边缘。请参阅下面的示例,我正在绘制一颗星星。<canvas id="myCanvas" width="150" height="150"></canvas><script> var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); function drawCurve(x, y, curves) { context.moveTo(x, y); for (i = 0; i < curves.length; i++) { c = curves[i] context.bezierCurveTo(c[0], c[1], c[2], c[3], c[4], c[5]); context.moveTo(c[4], c[5]); } context.stroke(); } data = [] numPoints = 12 size = 35 angle = 45 for (j = 0; j < numPoints; j++) { a = angle * Math.PI / 180 points = [] points.push(80 + Math.round(size / 2 * Math.sin(a))) points.push(80 + Math.round(size / 2 * Math.cos(a))) points.push(80 + Math.round(size * Math.sin(a))) points.push(80 + Math.round(size * Math.cos(a))) points.push(80 + Math.round(size * 2 * Math.sin(a))) points.push(80 + Math.round(size * 2 * Math.cos(a))) angle += 360 / numPoints data.push(points) } drawCurve(80, 80, data);</script>