So I'm trying to repeat a portion of my spritesheet as a background. So far, I have attempted this:

var canvas = $("#board")[0],
    ctx = canvas.getContext("2d"),
    sprite = new Image();
    sprite.src = "spritesheet.png";
sprite.onload = function(){
    ctx.fillStyle = ctx.createPattern(spriteBg, "repeat");
    ctx.fillRect(0, 25, 500, 500);

As you can see, it repeat the whole image, not just a part of it, and I just can't figure out how to do that last part.

  • 1
    \$\begingroup\$ stackoverflow.com/questions/8761670/… \$\endgroup\$ Oct 7, 2012 at 15:05
  • \$\begingroup\$ Mobil: If that solved your problem, you should post your conclusions as an answer. Then others with the same problem can find it too. \$\endgroup\$
    – Anko
    Dec 8, 2012 at 11:48
  • \$\begingroup\$ @KeithThomas Yea sorry. Posted my answer now :D \$\endgroup\$
    – Mobilpadde
    Dec 8, 2012 at 16:05

1 Answer 1


This'll do! :D

var sprite     = new Image(),
    sprite.src = "spritesheet.png",
    texture    = {y: 42, x: 2*14},
    ptrn       = generatePattern(sprite, texture.x, texture.y);
ctx.fillStyle  = ctx.createPattern(ptrn, "repeat");
ctx.fillRect(0, 0, 500, 500);

Thanks to @KeithThomas for linking to https://stackoverflow.com/questions/8761670/multiple-image-patterns-in-2d-context-of-html5-canvas

  • \$\begingroup\$ I'm confused by this answer, what is the generatePattern() method? I can't find any info on this online...did you mean to use createPattern() twice? Can you pass the x and y coordinates to this method instead of just "repeat"? \$\endgroup\$ Jan 13, 2014 at 4:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .