首页 > 解决方案 > 如何使用 CSS3、HTML5、SVG 和 Jquery 创建不规则曲线?

问题描述

我正在尝试制作一条不规则曲线,以便在我的网站上显示进度图。我已经使用 jQuery 进行了尝试,并且成功获得了 sin 波,但我想实现如下图所示的不规则波线。我怎样才能实现它?

请参见下图。 我想要的示例图像

html代码

<canvas height="500" width="600" id="my_canvas"></canvas>

jQuery 代码

var my_canvas=$('#my_canvas').get(0);
var gctx = my_canvas.getContext("2d");
gctx.stroke();
gctx.beginPath();
gctx.moveTo(10, 125);
gctx.lineWidth=1;
gctx.strokeStyle= '#f00040';
var x = [];
var y = [];
for (var angle = 0; angle <590; angle+=1){
gctx.lineJoin = 'round';
y.push(125 - 120*( Math.sin(( Math.PI/180 ) * angle)));
x.push(10 + angle);
gctx.lineTo((10 + angle),((125 - 120*( Math.sin(( Math.PI/180 ) * 
angle)))));
}
gctx.stroke();

标签: jquerycsssvghtml5-canvas

解决方案


我会这样做:为了绘制曲线,我需要一组点。我将使用二次贝塞尔曲线,其中点(第一个和最后一个除外)是控制点。因为显然您需要为笔画设置动画,所以我使用 SVG 完成了它。对于动画,我使用 CSS,如下所述:SVG 线条动画的工作原理

//An array of points used to draw the curve
let points = [
  {
    x: 10,
    y: 24
  },
  {
    x: 70,
    y: 110
  },
  {
    x: 117,
    y: 10
  },
  {
    x: 130,
    y: 142
  },
  {
    x: 200,
    y: 70
  },
  {
    x: 270,
    y: 143
  },
  {
    x: 320,
    y: 24
  }
];


// a function that draws the curve using the points as control points

function drawCurve(points) {
  //find the first midpoint and move to it
  var p = {};
  p.x = points[0].x;
  p.y = points[0].y;

  let d = `M${p.x}, ${p.y}`;
  //curve through the rest, stopping at each midpoint
  for (var i = 0; i < points.length - 2; i++) {
    var mp = {};
    mp.x = (points[i].x + points[i + 1].x) / 2;
    mp.y = (points[i].y + points[i + 1].y) / 2;
    d += `Q${points[i].x},${points[i].y},${mp.x},${mp.y}`;
  }
  //curve through the last point, back to the first midpoint
  d += `Q${points[points.length - 2].x},${points[points.length - 2].y}, ${
  points[points.length - 1].x
},${points[points.length - 1].y}`;
  track.setAttributeNS(null, "d", d);
  
  
  //for the animation
  //1. get the total path length
  let pathLength = track.getTotalLength();
  //2. set the stroke-dasharray and the stroke-dashoffset for the animation
  theUse.style.strokeDasharray = pathLength;
  theUse.style.strokeDashoffset = pathLength;
}

drawCurve(points);

function randomIntFromInterval(mn, mx) {
  return ~~(Math.random() * (mx - mn + 1) + mn);
}
#base{ 
  stroke:#ccc;
  stroke-width:5px;
  fill:none;
}

#theUse{
  stroke:black;
  stroke-width:1px;
  fill:none;
  animation: dash 5s linear forwards;
}


@keyframes dash {
  to {
    stroke-dashoffset: 0;
  }
}
<svg viewBox="0 0 330 200"  id="svg">
  <defs>
    <path id="track"  /></defs>
    
<use xlink:href="#track" id="base"  />    
<use xlink:href="#track" id="theUse"  /> 
    
</svg>


推荐阅读