javascript - 向下滚动页面时,HTML5 Canvas 上的 map 动画沿着路径移动

标签 javascript html animation svg canvas

我是 HTML5 CANVAS 新手。当我访问这个website时还有这个website ,我对这些奇特的 Action 感到惊讶,当我向下滚动时, map 将继续向下并显示信息。

考虑到性能,我想使用Canvas而不是纯SVG。如果我有一个带有路径(带有<路径>)的 map SVG文件,我怎样才能达到这种效果? (向下滚动页面时 map 移动的路径)

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

谢谢!!

最佳答案

要将 pn SVG 路径绘制到 Canvas ,您需要使用 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>

关于javascript - 向下滚动页面时,HTML5 Canvas 上的 map 动画沿着路径移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53587028/

相关文章:

Android动画格式?方法?

Android 在 View.layout(l,t,r,b) 之后不重绘

javascript - jQuery:仅获取 <td> 的 html

javascript - 使用 agm 库在 Angular 2 中创建多边形

javascript - 覆盖 ColorBox 打开/关闭过渡效果?

Javascript正则表达式出现后的第一个字符

javascript - 将 onclicklistener 重新附加到按钮

html - 按内容显示下拉菜单宽度

javascript - onmouseover 影响取消 span 标签中的换行符

javascript - 淡出旧元素,淡入新元素