如何使用 JavaScript 和 SVG 在滾動頁面時進行繪製?
若要使用 JavaScript 和 SVG 在滾動頁面時進行繪製,程式碼如下 −
示例
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
height: 2000px;
background: #f1f1f1;
}
svg {
position: fixed;
top: 15%;
width: 400px;
height: 210px;
margin-left: -50px;
}
</style>
</head>
<body>
<h1>Scroll Using JavaScript and SVG example</h1>
<svg>
<path
fill="none"
stroke="purple"
stroke-width="5"
id="polygon"
d="M 150 350 Q 150 50 250 150 Q 250 550 300 150 Q 350 50 400 300"/>
</svg>
<script>
var polygon = document.getElementById("polygon");
var length = polygon.getTotalLength();
polygon.style.strokeDasharray = length;
polygon.style.strokeDashoffset = length;
window.addEventListener("scroll", drawPoly);
function drawPoly() {
var scrollpercent = (document.body.scrollTop + document.documentElement.scrollTop) /
(document.documentElement.scrollHeight - document.documentElement.clientHeight);
var draw = length * scrollpercent;
polygon.style.strokeDashoffset = length - draw;
}
</script>
</body>
</html>輸出
上述程式碼將生成以下輸出 −

滾動到底部 −

廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP