【问题标题】:map animation on HTML5 canvas moving through the path when scrolling down page [closed]向下滚动页面时,HTML5画布上的地图动画在路径中移动[关闭]
【发布时间】:2019-05-04 08:24:11
【问题描述】:

我是 HTML5 CANVAS 的新手。当我访问这个website 和这个website 时,我对向下滚动时的奇妙动作感到惊讶,地图将继续向下并显示信息。

考虑到性能,我想使用 Canvas 而不是纯 SVG。如果我有一个带有路径的地图 SVG 文件(带有 ),我该如何实现这个效果? (向下滚动页面时地图移动的路径)

我可以搜索哪些关键字,或者任何人都可以提供一些指导 感谢您的帮助。

谢谢!!

【问题讨论】:

    标签: javascript html animation svg canvas


    【解决方案1】:

    要在画布上绘制 pn SVG 路径,您需要使用 Path2D。在下一个示例中,我使用输入类型范围为苹果的笔划设置动画。你可以使用滚动事件。

    // get the path's data
    var svgPathApple= ap.getAttribute("d");
    // get the path's length
    let paths_length = ap.getTotalLength();
    
    // initiate the canvas
    var c = document.getElementById("c");
    var ctx = c.getContext("2d");
    var cw = c.width = 500;
    var ch = c.height = 500;
    // create a new canvas path using Path2D
    var theApple = new Path2D(svgPathApple);
    
    
    ctx.lineDashOffset = -paths_length;
    ctx.setLineDash([paths_length]);
    ctx.stroke(theApple);
    // use the input type range to change the lineDashOffset
    ir.addEventListener("input",()=>{
      let v = ir.value;
      ctx.lineDashOffset = v;
      ctx.clearRect(0,0,cw,ch);
      ctx.stroke(theApple);
    })
    canvas,svg {
      border:1px solid
    }
    
    svg{display:none}
    <p><input id="ir" type="range" min="-909.682" value="-909.682" max="0" /></p>
    <canvas id="c"></canvas>
    <svg viewBox = "0 0 500 500">
      <path id="ap" d="M376.349,171.58 c0,0-37.276,22.484-36.094,60.946s31.438,61.577,42.012,63.313c4.127,0.678-24.314,57.988-42.039,72.189 s-36.067,17.159-64.47,5.917c-28.403-11.242-48.521,0.724-65.089,6.871s-36.687-0.361-63.905-39.415 s-57.396-129.585-15.976-173.964s87.574-26.627,100-20.71s34.32,5.325,59.172-5.917S363.922,153.237,376.349,171.58z" />
    </svg>

    【讨论】:

      【解决方案2】:

      这些动画都使用了一种技巧,它们根据页面或部分的距离有条件地绘制路径的路径点数。以下代码说明了这一点(比他们所做的要简单得多),其中 scrollAmount 将取决于您通过一个部分的距离。

      const canvas = document.getElementById('canvas');
      const ctx = canvas.getContext('2d');
      
      // 0-1.0 for how far you have scrolled through a section
      var scrollAmount = 0.5; 
      
      var trailPath = [ [0,0], [10,10], .. many points .., [20,10] ];
      ctx.beginPath();
      ctx.strokeStyle = 'blue';
      ctx.moveTo(trailPath[0][0],trailPath[0][1]);
      
      // only draw line until the point we are at, using floor to get us to an integer    
      for(var i=0; i < Math.floor(scrollAmount * trailPath.length); i++){
         ctx.lineTo(trailPath[i][0],trailPath[i][1]); 
      }
      ctx.stroke();
      

      第二个引用的页面是解析并从通过 Ajax 加载的 SVG 文件中提取路径,使用 querySelector 并将其转换为要迭代的点列表。它做了很多,但渲染路径的基本机制如上。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-12
        • 1970-01-01
        • 2014-03-17
        • 1970-01-01
        • 1970-01-01
        • 2015-07-04
        • 2012-04-27
        • 2020-09-30
        相关资源
        最近更新 更多