使用数组练习javascript同时循环

时间:2013-11-30 21:52:30

标签: javascript arrays canvas keydown simultaneous

我想keydown触发一个块的移动,然后用另一个keydown,添加另一个移动块。如果我再次打开,那么会出现另一个移动块。就像现在一样,keydown停止了第一个块的移动。我想让所有的块同时移动。这是代码。它也可以在jsfiddle http://jsfiddle.net/7eUEE/

上找到

谢谢!

var canvas = document.getElementById("canvas"); 
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext("2d");
var w = canvas.width;
var h = canvas.height;
window.addEventListener("keydown", addnew, true);
window.addEventListener("keydown", move, true);
var list = [];
var id = 0;
var color = 'blue';
var x = 0;
var y = 0;

window.onkeydown = function(s){
    s.preventDefault();
    if(!s){
        s = window.event;
    }

    var keycode;
    if(s.which){
        keycode = s.which;
    }else{
        keycode = s.keyCode;
    }

}
function box(id, color, x ,y){
    box.id = id;
    box.color = color;
    box.x = x;
    box.y = y;
}   

function addnew(e){
    e.preventDefault();
    if(!e){
        e = window.event;
    }                   

    //space
    if(e.keyCode == 32){
        list[id] = new box(id, color, x, y);
        id++;
        y = y + 100;
        box.y = y;
        box.color = 'red';
        console.log(box.y);
    }
}

list[0] = box(id, color, x ,y);

function move(e){
    e.preventDefault();
    if(!e){
        e = window.event;
    }                   

    //right
    if(e.keyCode == 39){
        list[id];
        setInterval(loopdraw);
    }
}

var loopdraw = function draw(){
    box.x = box.x + 1;
    console.log(box.x);
    ctx.beginPath();
    ctx.fillStyle = box.color;
    ctx.fillRect(box.x, box.y, 50, 50);
    ctx.closePath();
}

1 个答案:

答案 0 :(得分:1)

您的Box对象的行为与对象不同,因为您可以通过3种方式使用它们:

  • class:list[id] = new box(id, color, x, y);
  • 功能:list[0] = box(id, color, x ,y);
  • 对象:box.y = y;box.color = 'red';

list部分是正确的:保留一组(移动)框。循环部分不是,因为您不使用该列表。你只能“循环”1个盒子。

我已更新小提琴:http://jsfiddle.net/rudiedirkx/7eUEE/1/我已将box类重命名为Box,因为可能有Box个对象名为box

重要部分:

// Create initial box
list[id++] = new Box(id, color, x ,y);

// Create more boxes
list[id++] = new Box(id, 'red', x, y);

// Loop through existing boxes animation
function loopdraw() {
  list.forEach(function(box) {
    // Draw