I am starting to develop my fist bigger game in HTML5 and struggling a bit with sprites. I can cut out single items, but I need to repeat them as well. For example, I have a battle ground that consists of grass, dirt path, building and a pond. I have all these in one sprite. But what I really need is to cut out the grass and repeat is as background on whole canvas.

I cannot believe that this wouldn't be possible, using sprites would loose almost completely point there... (apart from single static items of course).

I would appreciate if someone would have solution to this.


You're looking to use an HTML5 pattern - this is documented several places around the web so I'll spare the code implementation. A helpful example can be found here.

  • \$\begingroup\$ Please read my question better. I need to create a repeating background from one of the images in sprite. What you referring to I know very well, but you can create pattern only from one single image. Not from item in image sprite. Im not gonna downvote your answer, at least you wrote something, but it is not good answer. Thanks \$\endgroup\$ – Tomas Feb 19 '13 at 5:48
  • \$\begingroup\$ @Tom Hi Tom, if the pattern API does not do what you need; have you considered just using drawImage with the suitable overload? context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height); Then, just apply the tiling algorithm yourself. \$\endgroup\$ – Vaughan Hilts Feb 19 '13 at 5:57
  • \$\begingroup\$ Hi, I can draw the picture it self from sprite, I can even stretch it through whole canvas but as you cna imagine that doesnt look good. I am not sure what you mean by "Then apply tiling algorithm", but if you mean basically loop drawImage(), I thought about that too, but also thought that it cannot be good for performance.. is it ? \$\endgroup\$ – Tomas Feb 19 '13 at 6:22
  • \$\begingroup\$ @Tom No, it's not good for performance... if you do it every frame. What I've done before is setup a seperate canvas and called it 'background'. You simply make it the canvas below on the index page and render to it once - without a game loop. Then you won't have to re-render it and there's no performance hit. :) \$\endgroup\$ – Vaughan Hilts Feb 19 '13 at 18:23
  • \$\begingroup\$ A quick comment about profiling. Resist the temptation guess about whether or not something is good/bad for performance, and use a profiler instead. Chrome, for example, has a profiler built in to the dev console. So if something is "good enough", go with it until your profiler says otherwise. In the context of this question, just use drawImage() in loop to start with. It's simple and you can optimize if necessary later. Make it work, then make it fast. =) \$\endgroup\$ – larsbutler Apr 16 '13 at 16:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.