【问题标题】:Move a canvas up and down - html5 / css3上下移动画布 - html5 / css3
【发布时间】:2023-10-19 04:02:02
【问题描述】:

我通过用户输入的大小和颜色创建了一个画布元素。 我想让画布在页面上连续上下移动。我怎样才能做到这一点? 下面是html文件:

<!DOCTYPE html>
    <html>
    <body>
        <script src="pol.js" >
        </script>
    </body>
    </html>

以下是javascript文件“pol.js”:

var h=prompt("Provide length of square");
var col=prompt("Provide the color");
document.write('<div id="float" ><canvas id="myCanvas" width="'+h+'" height="'+h+'" style="border:1px solid #c3c3c3;"> </canvas> </div>');
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle=col;
ctx.fillRect(0,0,h,h);

【问题讨论】:

  • move up and down the page continuously”到底是什么意思?您的意思是希望元素在用户滚动页面时跟随用户?
  • 不,我的意思是它应该动画地上下摆动一个固定的长度。

标签: javascript html css canvas


【解决方案1】:

以下 CSS 应该在页面顶部和向下 500px 之间平滑地移动画布元素:

<style type="text/css">
    @keyframes moveabout {
        from { top: 0px; }
        to   { top: 500px; }
    }
    #float {
        position: absolute;
        animation: moveabout 5s ease-in-out infinite alternate;
    }
</style>

更多信息: http://www.w3schools.com/css/css3_animations.asp

如果你想将元素从页面的顶部移动到底部,你可以使用 document.windowHeight 来获取窗口的视口高度。

【讨论】: