javascript - 如何用js动画画布
问题描述
我正在尝试使用 html canvas 制作动画,但我不知道我是否有最好的方法。
我正在尝试<canvas id="canvas"></canvas>
使用fillRect()
.
然后我正在执行一个函数 onload,它的超时时间为 500 毫秒。
该函数基本上通过更改其 x 或 y 将矩形 1px 绘制到我想要的位置,然后使用clearRect()
,我在从起点开始并跟随另一个矩形后的某个时间创建矩形。
我这样做对吗?还是有更好的方法来解决它?
解决方案
你可以使用这个结构
const canvas = document.getElementById('can');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.backgroundColor = 'white';
var someconstructorName = function(paramA,paramB,...){
"Initialisation of variables and other things"
this.draw = function(){
"your logic"
}
this.update = function(){
"your update logic"
this.draw();
}
}
function animate(){
requestAnimationFrame(animate)
}
animate();
在这里查看这支 Pen,它会给你一个好主意: https ://codepen.io/khanChacha/pen/YgpBxM
推荐阅读
- reactjs - 是否可以在 componentDidMount 以外的任何方法中使用 axios get 方法?
- java - 避免为每条记录重新初始化 groovy shell
- reactjs - axios调用成功响应后如何重定向
- sql - postgresql:在选择中使用聚合辅助函数的结果
- javascript - 如何从 jQuery 中的同名 div 中获取当前选定的 div 元素?
- python - 在基于多列的数据框中创建缓冲区 - Python
- amazon-web-services - 如何使用 Gitlab CI 和 aws cdk 实现 CD
- java - 将文件替换为由 mvn 包生成的 WAR 文件
- c - 可以在循环的括号内定义循环变量吗?
- ios - 添加 NavigationLink 时的 Swiftui 问题