我有我认为的错误模拟器的良好基础,但我没有得到我想要的动画运动。
使用画布在动画中创建移动流体运动的最佳方法是什么。
我是 javascript 新手,只是在乱搞,所以也欢迎任何改进我的编码标准的建议。
谢谢
HTML
<canvas width="578" height="200" margin="3px" id="targer" style="border: 1px solid black;"></canvas>
JAVASCRIPT
var canvas = document.getElementById('targer');
function bugObj(x, y, size) {
this.x = x;
this.y = y;
this.size = size;
this.update = function(move) {
var p = Math.floor((Math.random()*3)-1) + this.x;
var q = Math.floor((Math.random()*3)-1) + this.y;
if (p > canvas.width) { p = canvas.width };
if (p < 0) { p = 0 };
if (q > canvas.height) { q = canvas.height };
if (q < 0) { q = 0 };
this.x = p;
this.y = q;
}
return this;
}
function popBugs(){
var bug;
var ctv = canvas.getContext('2d');
ctv.fillStyle = 'black';
ctv.fillRect(0, 0, canvas.width, canvas.height);
for(var i = 0; bug = bugs[i]; i++) {
ctv.fillStyle = 'yellow';
ctv.fillRect (bug.x, bug.y, bug.size, bug.size);
}
}
var bugs = [],
numberbugs = 100,
x,y;
for (var i = 0; i < numberbugs; i++){
x = Math.random()*canvas.width;
y = Math.floor(Math.random()*canvas.height);
bugs.push(new bugObj(x, y, 2));
}
function loop() {
/// update each bugs objects
for(var i = 0;i < bugs.length; i++) bugs[i].update();
popBugs();
requestAnimationFrame(loop);
}
loop();
window.requestAnimationFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000);
};
})();