canvas中如何在多点之间 平滑的画出一条线,类似动画的那种 急急急!!!

以下是我的代码,

 var content = document.getElementById('weatherForecastCanvas');
    var ctx = content.getContext("2d");
    ctx.strokeStyle = "#fff";
    ctx.fillStyle = "#fff";
    ctx.lineWidth = 3;


//最高1

    ctx.arc(xPoints[0], yPoints[0], 3, 0, Math.PI * 2, true);

////////////////////开始最高温度的线///////////////////////////////

    ctx.fillText("" + a[0] + "℃", xPoints[0] - 10, yPoints[0] + 20);
    ctx.moveTo(xPoints[0], yPoints[0]);
    ctx.lineTo(xPoints[1], yPoints[1]);

//最高2

    ctx.arc(xPoints[1], yPoints[1], 3, 0, Math.PI * 2, true);
    ctx.fillText("" + a[1] + "℃", xPoints[1] - 10, yPoints[1] + 20);
    ctx.moveTo(xPoints[1], yPoints[1]);
    ctx.lineTo(xPoints[2], yPoints[2]);
阅读 14.1k
5 个回答

平滑曲线是做高阶贝塞尔曲线吗

感觉题主要的是类似这样的?
既然要一点点的话,那就把画的动作定时的来操作,一点点的画线,看下面示例代码

 var canvas = document.querySelector('canvas'),
               context = canvas.getContext('2d'),
               w, h;
               w = canvas.width = window.innerWidth;
               h = canvas.height = window.innerHeight;
           
     var x=y=0;
     var maxX = 200,
          maxY = 200;
     var interVal ;
          context.strokeStyle = "red";
          context.fillStyle = "blue";
          context.lineWidth = 3;
            
          //定时画  
          function draw(){
            if(x<maxX&&y<=maxY){
              context.lineTo(x+=10, y+=10);
              context.stroke();
            }else{
              clearInterval(interVal);
            }
          }
          //另一种画
           function drawFrame(){
              interVal = window.requestAnimationFrame(drawFrame, canvas);
               if(x<maxX&&y<=maxY){
                context.lineTo(x+=10, y+=10);
                context.stroke();
               }else{
                window.cancelAnimationFrame(interVal);
               }
           }

           context.moveTo(x,y);
            
         // interVal = setInterval(draw, 500);
           
        drawFrame();

以下是一种通配解法,利用canvas的setLineDash和lineDashOffset, 可以模拟出来平滑的画线,具体原理可以自己一点一点调数据来试试,想必不难理解。

算了,直接搞成坐标容易理解。 假设画(a, b) 到 (c, d)的线段.

    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    // length是两坐标之间的距离
    var length = Math.sqrt( (a-c)*(a-c) + (b-d)*(b-d) );

    function move() {
        if(length <= 0) {
            return;
        }
        ctx.clearRect(0, 0, 500, 500);
        ctx.setLineDash([length, length]);
        ctx.lineDashOffset = length--;
        ctx.moveTo(a, b);
        ctx.lineTo(c, d);
        ctx.stroke();
        requestAnimationFrame(move);
    }
    move()

这样,这条线就一点一点画出来了。

推荐问题