[habr] Canvas: images. Example #4

http://habrahabr.ru/post/111385/

by oleg3190

HTML

<canvas id='example'>Обновите браузер</canvas>

CSS

canvas {
    border: 1px solid #ccc;
}

JavaScript

var example = document.getElementById("example"),
    ctx = example.getContext('2d'),
    cellSize = 32,
    pic = new Image(),
    map = 
    [
      [{x:1,y:3},{x:1,y:3},{x:1,y:4},{x:1,y:4},{x:1,y:4},{x:1,y:4},{x:1,y:4},{x:1,y:4}],
      [{x:1,y:4},{x:1,y:1},{x:2,y:1},{x:3,y:1},{x:1,y:4},{x:1,y:4},{x:1,y:4},{x:1,y:4}],
      [{x:1,y:4},{x:1,y:2},{x:2,y:2},{x:3,y:2},{x:1,y:4},{x:1,y:3},{x:1,y:3},{x:1,y:3}],
      [{x:1,y:4},{x:3,y:4},{x:2,y:3},{x:3,y:4},{x:1,y:4},{x:1,y:3},{x:1,y:4},{x:1,y:4}],
      [{x:1,y:4},{x:3,y:4},{x:2,y:4},{x:3,y:4},{x:1,y:4},{x:1,y:3},{x:1,y:4},{x:1,y:4}],
      [{x:1,y:4},{x:1,y:4},{x:1,y:3},{x:1,y:4},{x:1,y:4},{x:1,y:3},{x:1,y:4},{x:1,y:4}],
      [{x:1,y:4},{x:1,y:4},{x:1,y:3},{x:1,y:3},{x:1,y:3},{x:1,y:3},{x:1,y:4},{x:1,y:4}],
      [{x:1,y:4},{x:1,y:4},{x:1,y:4},{x:1,y:4},{x:1,y:4},{x:1,y:4},{x:1,y:4},{x:1,y:4}]
    ];
example.width = 8 * cellSize;
example.height = 8 * cellSize;
pic.src = 'http://habr.habrastorage.org/post_images/e85/727/cb1/e85727cb1a88099325eaf5b243d4c41f.png';
pic.onload = function () {
    for (var j = 0; j < 8; j++) {
        for (var i = 0; i < 8; i++) {
            ctx.drawImage(pic, (map[i][j].x - 1) * cellSize, (map[i][j].y - 1) * cellSize, 32, 32, j * cellSize, i * cellSize, 32, 32);
        }
    }
}