逐渐清除画布上下文(鼠标轨迹?)

时间:2019-03-14 11:31:56

标签: javascript canvas html5-canvas mouseevent

如果看到运行的代码段,则将这个html canvas绘图内容分割成彩色,以渐变形式显示弧。

我正在尝试找出如何从图形的尾端逐渐清除旧的“弧”的上下文,类似于“鼠标跟踪”效果,也许类似于:https://imgur.com/a/2Lr9IYq

我在想,也许是这样,一旦total计数器超过segment计数,它就会清除自身,但我不确定如何执行此操作。

如果有人能指出我正确的方向,将不胜感激!

var c = document.querySelector("canvas"),
        ctx = c.getContext("2d"),
        colors = [
          {r: 0, g: 0, b: 0, a:1},
          {r: 255, g: 255, b: 255, a:1},
        ],
        cIndex = 0, maxColors = colors.length,
        total = 0, segment = 1000,
        isDown = false, px, py;


    setSize();
          
    c.onmousedown = c.ontouchstart = function(e) {
      isDown = true;
      var pos = getPos(e);
      px = pos.x;
      py = pos.y;
    };

    c.onmousemove = c.ontouchmove = function(e) {if (isDown) plot(e)};
    c.onmouseup = c.ontouchend = function(e) {
      e.preventDefault();
      isDown = false
    };

    function getPos(e) {
      // e.preventDefault();
      if (e.touches) e = e.touches[0];
      var r = c.getBoundingClientRect();
      return {
        x: e.clientX - r.left,
        y: e.clientY - r.top
      }
    }

    function plot(e) {
      var pos = getPos(e);
      plotLine(ctx, px, py, pos.x, pos.y);
      px = pos.x;
      py = pos.y;
    }

    function plotLine(ctx, x1, y1, x2, y2) {

      var diffX = Math.abs(x2 - x1),
          diffY = Math.abs(y2 - y1),
          dist = Math.sqrt(diffX * diffX + diffY * diffY),
          step = dist / 50,
          i = 0,
          t, b, x, y;
      
      while (i < dist) {
        t = Math.min(1, i / dist);

        x = x1 + (x2 - x1) * t;
        y = y1 + (y2 - y1) * t;



        // ctx.shadowBlur = 500;
        // ctx.shadowOffsetX = 0;
        // ctx.shadowOffsetY = 0;
        // ctx.shadowColor = getColor();

        // console.log(getColor())
        ctx.fillStyle = getColor();
        ctx.beginPath();
        ctx.arc(x, y, 25, 0, Math.PI*2);

        ctx.fill();
        i += step;
      }
      
      function getColor() {
      
        var r, g, b, a, t, c1, c2;
        
        c1 = colors[cIndex];
        c2 = colors[(cIndex + 1) % maxColors];
        t = Math.min(1, total / segment);
        
        if (++total > segment) {
          total = 0;
          if (++cIndex >= maxColors) cIndex = 0;
        }
      
        r = c1.r + (c2.r - c1.r) * t;
        g = c1.g + (c2.g - c1.g) * t;
        b = c1.b + (c2.b - c1.b) * t;
        a = c1.a + (c2.a - c1.a) * t;
        

        return "rgb(" + (r|0) + "," + (g|0) + "," + (b|0) + "," + (a) + ")";
      }
    }

    window.onresize = setSize;
    function setSize() {
      c.width = window.innerWidth;
      c.height = window.innerHeight;
    }
html, body {
      margin:0;
      padding:0;
    }

 
    body {
      padding: 0px;
    }
<canvas id="myCanvas" ></canvas>

0 个答案:

没有答案