سؤال

EDITED: The following renders sprite sheet images; now I need to give different behavior to each entity: key movement to boy, random animation to owl. I can do this with isolated images, but where/how to include behavior for each drawImage instance? Thanks.

<script>
var width = 50,
        height = 50,
        frames = 3,

        currentFrame = 0,

        canvas = document.getElementById("myCanvas");
        ctx = canvas.getContext("2d");
        image = new Image();
        image.src = "sprites.png"

        var draw = function(){
                ctx.clearRect(200, 400, width, height); //boy
                ctx.clearRect(150, 300, width, height); //owl
                ctx.clearRect(50, 400, width, height); //goat

                ctx.drawImage(image, 0, height * currentFrame, width, height, 200,400, width, height); //boy

                ctx.drawImage(image, 50, 50 * 2, width, height, 150, 300, width, height); //owl

                ctx.drawImage(image, 150, 50 * currentFrame, width, height, 50, 400, width, height); //goat

                ctx.drawImage(image, 100, 50 * 3, width, height, 150, 400, width, height); //bush


                if (currentFrame == frames) {
                  currentFrame = 0;
                } else {
                  currentFrame++;
                }
        }

        setInterval(draw, 550);
هل كانت مفيدة؟

المحلول

You could create a function to get the tile position and size based on the spritesheet layout. This makes these sort of things easier to handle. Provide index [0, 15] and you'll get back an object with the tile's position:

function getTile(index) {

    var row = (index / 4)|0,   // line
        col = index % 4,       // column
        w = 50,                // tile width and height
        h = 50;

    return {
        x: col * w,
        y: row * h,
        w: w,
        h: h
    }
}

The drawImage() method works this way (for this overload):

drawImage(image, sx, sy, sw, sh,  dx, dy, dw, dh);

where s* are the source coordinates in your spritesheet, and d* is destination position and size for the clipped region you get from the s* coordinates.

So here you could do:

var width = 50,
    height = 50,
    frames = 16,
    currentFrame = 0,
    canvas = document.getElementById("myCanvas"),
    ctx = canvas.getContext("2d"),
    image = new Image();

image.onload = function() {
    setInterval(draw, 400);  // start when image has finished loading
}
image.src = "sprites.png"

function draw(){

    ctx.clearRect(0, 0, width, height);

    var tile = getTile(currentFrame);        
    ctx.drawImage(image, tile.x, tile.y, tile.w, tile.h, 0, 0, width, height); 

    currentFrame++;

    if (currentFrame === frames) {
      currentFrame = 0;
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top