当向下滚动页面时,HTML5画布上的地图动画在路径上移动



我是HTML5 CANVAS的新手。当我访问这个网站和这个网站时,我惊讶于当我向下滚动时,地图会继续向下滚动并显示信息。

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

我可以搜索什么关键词,或者任何人都可以提供一些方向感谢您的帮助。

谢谢!!

要绘制到画布的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>

这些动画都使用了一种技巧,根据页面或部分的向下距离,有条件地绘制轨迹的路径点数量。下面的代码说明了这一点(比它们做的要简单得多(,其中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();

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

最新更新