通过canvas每20ms绘制出一个对象?



 //定义一个对象
function Flycar(x, y){
   this.x = x;
   this.y = y;
 }
//绘制这个对象
function drawflycar(flycar){
   flyCar.beginPath();
   flyCar.fillRect(flycar.x, flycar.y, 50,50); 
   flyCar.fillStyle='blue';;
}
 setInerval(function(){
    var flycar = new Flycar(flyX,flyY);  //每20ms实例化一个对象,flyX,flyY是随机产生的一个坐标
    flyArr.push(flycar);   //添加到数组中
    for(x in flyArr){
         drawflycar(flyArr[x]);            //遍历这个数组,绘制出数组中的对象
       }
    },20)

想实现每20ms绘制出一个矩形
我这么写没有实现,错在哪里,或者要实现这个需求应该怎么写?

jquery canvas html5 JavaScript

我纯洁我骄傲 9 years, 10 months ago

 <canvas height="480" width="480" ></canvas>
<script>

var canvas = document.querySelector("canvas");
var context = canvas.getContext("2d");
var flyArr = [];

function Flycar(x, y){
    this.x = x;
    this.y = y;
}

function drawflycar(flycar){
    context.fillStyle = "blue";
    context.fillRect(flycar.x,flycar.y,50,50);
}

setInterval(function(){
    var x = Math.floor(Math.random()*canvas.offsetWidth);
    var y = Math.floor(Math.random()*canvas.offsetHeight);
    flyArr.push(new Flycar(x,y));
    // console.log(flyArr);
    flyArr.forEach(function(){
        drawflycar(arguments[0]);
    });
},20);

</script>

蛋疼D別扭控 answered 9 years, 10 months ago

推荐你看本书吧,
html5 canvas 核心技术
另外这个网站上可以同步看运行结果和书中练习。

konomi控 answered 9 years, 10 months ago

Your Answer