簡體   English   中英

多重設定間隔時間

[英]Multiple set Interval time

在此動畫中,我為兩個球制作了兩個函數,但是在畫布中沒有第二個球。 我的兩個球的代碼-

function draw() {
    ctx.clearRect(0, 0, 300, 300);
    //ctx.beginPath();
    //ctx.arc(x, y, 10, 0, 2 * Math.PI, true);
    //ctx.closePath();
    ctx.drawImage(img, x, y, 20, 20);
    ctx.fill();
    x += dx;
    y += dy;

    bounce();
}
function draw2()

{
    ctx.clearRect(0,0,300,300);
    ctx.beginPath();
    ctx.arc(x, y, 10, 0, 2 * Math.PI, true);
    ctx.closePath();
    ctx.fill();
    x += dx;
    y += dy;
    bounce();
}

調用函數

    function init() {
        var ctx = document.getElementById("canvas").getContext("2d");

        return setInterval(draw, 10);
return setInterval(draw2,20);
                   //This is how i am calling both function 

}

我們可以用Java語言做到嗎?

預期結果-

兩個球都來自同一位置,我想當第一個球在畫布框架中反彈時,僅在10毫秒后, draw2 ()另一個球應進入框架並以相同的方式動作。

小提琴-http: //jsfiddle.net/stackmanoz/B6XZC/4/

為了使此工作正常進行,您將需要將繪畫功能與畫布清除代碼分開,並具有一個滴答/輪詢循環,該循環與希望球出現的時間是分開的。

您不妨使用JavaScript構造函數的功能來幫助您解決問題。

function ball( ctx, x, y, dx, dy ){
  this.img = ? /// you'll have to set your image, whatever it is.
  this.x = x||0;
  this.y = y||0;
  this.dx = dx||0;
  this.dy = dy||0;
  this.draw = function(){
    ctx.drawImage(this.img, this.x, this.y, 20, 20);
  }
  this.tick = function(){
    this.x += this.dx;
    this.y += this.dy;
    this.draw();
  }
}

然后使用以下內容處理圖形。

function clear( ctx, cnv ){
  ctx.clearRect(0, 0, 300, 300);
  /// a faster way to clear can be: 
  /// cnv.width += 0; 
  /// or:
  /// cnv.width = cnv.width;
}

/// you should always have a core loop that delegates to other functions/objs
function loop( cnv, ctx, balls ){
  clear(ctx, cnv);
  for( var i=0; i<balls.length; i++ ){
    balls[i].tick()
  }
}

function init() {
  var cnv = document.getElementById("canvas");
  var ctx = cnv.getContext("2d");
  /// create the first ball and add it to your ball list
  var balls = [new ball(ctx,50,0,1,1)];
  /// 10ms wait before the extra ball is added
  setTimeout(function(){balls.push( new ball(ctx,100,0,1,1) );},10); 
  /// this will be your animation loop
  return setInterval(function(){loop(cnv, ctx, balls)}, 10);
}

上面的內容是手工輸入的,未經測試,可以大大改善..但是它應該起作用,並給您一個想法。

draw()draw2()清除畫布,因此您只會看到最新的更新。 另外,您還有一個全局xydxdy ,這意味着您的兩個球將永遠繪制在完全相同的位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM