简体   繁体   中英

moving the position of an image one block at a time

i was wondering how i would move my picture(the green block) down the already created blocks one block at a time, i would like to do it someway without using setinterval like through a for loop or an if statement to increment x or something, any suggestions? here is a link to a jsfiddle http://jsfiddle.net/ueo30Lg0/

var rows = 20;
var cols = 10;
var size = 32;
function drawBoard(){
    ctx.fillStyle="#D3D3D3";
ctx.fillRect( 0,55,320, 400);
    var colors = ['#FFFFFF','#000000'];
       var squares = colors;
var square = 0;
canvas = document.getElementById('gameCanvas');
canvas_width = canvas.width;
canvas_height = canvas.height;
for(var row=0; row<rows; row++) {
    for(var col=0; col<cols; col++) {
        var x = col*size;
        var y = row*size;

        ctx.fillStyle = squares[square++%colors.length];
        ctx.fillRect(x,y,size,size);



    }
    square += colors.length-1;
}
}

and here is where the block i want to move is

var logo2 = new Image();
logo2.src = 'http://hdwallphotos.com/wp-content/uploads/2014/02/Green-Background-Image-CSS-Wallpaper.png'

function blocks(){
logo2.onload = function(){
canvas = document.getElementById('gameCanvas');
ctx = canvas.getContext('2d');
for(var row=0; row<rows; row++) {
    for(var col=0; col<cols; col++) {
        var x = col;
        var y = row;

ctx.drawImage(logo2, x,y,23,13);
    }

}
};
}

Don't have enough cred for a comment, but there's a pretty good example of a Javascript game loop (that I've since used/modified slightly for my own purposes) found here (see yckart's answer): requestAnimationFrame at a limited framerate Check it out and see if that helps.

EDIT: I've forked your fiddle, and added in a very basic loop - just a call to setInterval, so it will call our main() function over and over, and allow us to draw the green square in a new position each time - and removed the image loading for the green square (why not just use a green rectangle, as you're doing for the board, already?)

I've removed some redundancy, and I think, simplified things somewhat.

Check it out here: http://jsfiddle.net/v4nz666/14yLvo08/

the basic gist is (though I've got no bound-checking here, it is in the fiddle):

function main() {
    drawBoard();
    drawGreenBlock();
    y++;
}

setInterval(main, 30);

As I mentioned, this is a very simple way of doing a game loop in JS there are better approaches. See the answer I've linked above for a much nicer solution, which uses browsers' optimized method requestAnimationFrame().

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM