1

I'm drawing a world map onto a HTML5 canvas. I need the world map to repeat vertically and horizontally. I'm dynamically appending the world map, as an img tag, to a div on my web application and spriting it to display different parts of the world (depending on the data passed in elsewhere in the script). If, for example, Asia takes up the left half of the div, and say, not the Americas, then I don't want a blank space to appear on the right. I want the map to start repeating. So I'll need the image drawn on the canvas to repeat.

I found this on stackoverflow elsewhere but it doesn't work for me. D:

createFullMapImage: function(done){
var imageObj = new Image();

imageObj.onload = _.bind(function(){
   var canvas = document.createElement("canvas"),
       context = canvas.getContext('2d'),
       w = imageObj.width,
       h = imageObj.height;

   canvas.width = w;
   canvas.height = h;

   for(var w = 0; w < canvas.width; w += imageObj.width){
      for(var h = 0; h < canvas.height; h += imageObj.height){
          context.drawImage(imageObj, w, h);
      }
   }
   var canvasImage = canvas.toDataURL('image/png');
   done.call(this, canvasImage);
}, this);
imageObj.src = [src]
}

P.S. I've tried setting a div with a background-image property to the URL of the world map, and setting background-repeat, but that distorts the size I want, for some reason.

Thx --Gaweyne

EDIT -- RE: Duplicate. As a newbie to HTML5 canvas, wasn't clear to me, from the other thread on the same topic, whether I use the .fillRect() method in conjunction with the .drawImage() method when making the image src repeat on the canvas. The answerer to this thread helped clarify.

  • 1
    Use `ctx.createPattern` to repeat a bitmap image. Set the `fillStyle` to the pattern and then draw a rectangle over the area you want the image repeated. – Blindman67 Oct 13 '15 at 13:48
  • ... But I might have been doing it wrong. How would you modify the above code, using the .createPattern() method? –  Oct 13 '15 at 13:50

1 Answers1

2

Using pattern repeat

// img is the image, ctx is the 2d context.
var pat=ctx.createPattern(img,"repeat");  // repeat the image as a pattern
ctx.fillStyle=pat;   // set the fill style
ctx.rect(0,0,150,100);  // create a rectangle
ctx.fill();            // fill it with the pattern.
Blindman67
  • 51,134
  • 11
  • 73
  • 136