这是我的第一篇文章(如果有任何错误,我很抱歉)。 我正在尝试用画布制作类似“圆形进度条”的东西。我是一个完整的画布新手。 当我向下滚动时,该程序可以运行,但当我向上滚动时,它不会“返回”。
(也请原谅我的英语不好)
这是代码:
<canvas id="canvas" width="200" height="200" style="position:fixed;"></canvas>
<h1 style=" position: fixed;">scroll up and down to view the progress</h1>
<div id="content" style="height: 3000px;">
<!-- -----------------------SCRIPTS ----------------------- -->
<script>
var body = document.body
var myCanva = document.getElementById('canvas')
window.addEventListener('scroll', (e) => {
let alto = body.offsetHeight - window.innerHeight
let posY = window.scrollY
let grados = (360 * (posY / alto)) //grados porcentuales según scroll
let endAngle = (Math.PI / 180) * grados
console.log(endAngle)
const ctx = myCanva.getContext("2d")
ctx.beginPath();
ctx.arc(100, 100, 50, 0, endAngle)
ctx.lineWidth = 20;
ctx.stroke()
}
)
</script>
你只需要将
ctx.clearRect(0,0, myCanva.width, myCanva.height);
添加到滚动事件监听器中。 https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/clearRect
var body = document.body
var myCanva = document.getElementById('canvas')
window.addEventListener('scroll', (e) => {
let alto = body.offsetHeight - window.innerHeight
let posY = window.scrollY
let grados = (360 * (posY / alto)) //grados porcentuales según scroll
let endAngle = (Math.PI / 180) * grados
//console.log(endAngle)
const ctx = myCanva.getContext("2d")
ctx.clearRect(0, 0, myCanva.width, myCanva.height);
ctx.beginPath();
ctx.arc(100, 100, 50, 0, endAngle)
ctx.lineWidth = 20;
ctx.stroke()
})
<canvas id="canvas" width="200" height="200" style="position:fixed;"></canvas>
<h1 style=" position: fixed;">scroll up and down to view the progress</h1>
<div id="content" style="height: 3000px;"></div>