开发者

Modifying HTML5 snake game with image file for head

I've followed a tutorial on how to create a HTML5 Snake game but I want to modify it. The tutorial can be found at http://blog.new-bamboo.co.uk/2009/12/30/html5-canvas-snake-game

I want to have an image file for the head of the snake which is 10x10 pixels while the rest of the snake is the regular color. Could anyone help me accomplish this with the code from the tutorial?

Imagine that this is the snake and [x] represents the head. I would like to modify the head to contain an image.

[x][ ][ ][ ]

I know that to draw an image in the ca开发者_Go百科nvas you would use the drawImage method, but don't know how to use it for this specific game.

Thx in advance :)


After this line... this.gridSize = 10; add

this.snakeHead = new Image();
this.snakeHead.src = "/path/to/my/image.png";

Then rewrite the following function like this...

function drawSnake() {
  snakeBody.push([currentPosition['x'], currentPosition['y']]);
  ctx.drawImage(snakeHead,currentPosition['x'], currentPosition['y'],gridSize,gridSize);
  if(snakeBody.length > 1) {
    last = snakeBody[1];
    ctx.fillRect(last['x'], last['y'], gridSize, gridSize); // this might be last[0] and last[1] here
  }
  if (snakeBody.length > 3) {
    var itemToRemove = snakeBody.shift();
    ctx.clearRect(itemToRemove[0], itemToRemove[1], gridSize, gridSize);
  }
}

I haven't run this, this is a guide only to get you started.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜