在画布中同时从Sprite表中渲染多个部分?

时间:2014-04-28 03:21:18

标签: html5 canvas html5-canvas sprite sprite-sheet

EDITED:以下内容呈现精灵表图像;现在我需要为每个实体提供不同的行为:男孩的关键动作,猫头鹰的随机动画。我可以用孤立的图像做到这一点,但是在哪里/如何包含每个drawImage实例的行为?感谢。

<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);

1 个答案:

答案 0 :(得分:1)

您可以创建一个函数来根据spritesheet布局获取切片位置和大小。这使得这些事情更容易处理。提供索引[0,15],你将获得一个具有图块位置的对象:

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
    }
}

drawImage()方法以这种方式工作(对于此重载):

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

其中s *是spritesheet中的坐标,d *是从s *坐标获得的剪裁区域的目标位置和大小。

所以你可以这样做:

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;
    }
}
相关问题