Canvas How to - Draw an image grid








Question

We would like to know how to draw an image grid.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
function init() {<!--from www  . jav a  2  s  .  co m-->
    var canvas = document.getElementById("canvas");
    context = canvas.getContext("2d");
    images = new Array();
}
function drawImage() {
    for (var i = 0; i < 12; i++) {
        for (var j = 0; j < 12; j++) {
            var index = i * 12 + j;
            images[index] = new Image();
            images[index].src = 'http://www.java2s.com/style/download.png';
            images[index].onload = dumb(context, images[index], index, i, j);
        }
    }
}
window.onload = init;
function dumb(ctx,img,index,i,j){
    return function () {
        ctx.drawImage(img, i * 20, j * 20, 20, 20);
    };
}
</script>
</head>
<body>
  <canvas id="canvas" width="300px" height="300px" style="border: solid;"></canvas>
  <button onclick="drawImage();">Display Image</button>
</body>
</html>

The code above is rendered as follows:

Another example


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--from w w w  .j  a v a2  s.co  m-->
    var can = document.getElementById('canvas1');
    var ctx = can.getContext('2d');
    var img = new Image();
    img.onload = function() {
        var s = 5;
        ctx.scale(s, s); // visible edges in FIREFOX
        for (var x = 0.3; x < 200; x+=15) {
            for (var y = 0.3; y < 200; y+=15) {
                ctx.drawImage(img, 0, 0, 15+1/s, 15+1/s, x, y, 15+1/s, 15+1/s);
            }
        }
    }
    img.src = "http://www.java2s.com/style/download.png";
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas1" width="400" height="400"></canvas>
</body>
</html>

The code above is rendered as follows: