Search code examples
htmlcanvasrepeatsprite-sheet

Using a sprite sheet with createPattern()


I can't seem to find any solid info on how to do this, so I'm wondering if someone can point me in the right direction.

I have a large sprite sheet, let's call it textures.png. Each texture is 64x64 pixels and I need to be able to create patterns out of these textures.

createPattern() is a great function but it seems to only take two arguments, the image source and whether to repeat it or not. This is fine if you are loading a single image for each texture, but I'm wondering how to do this using textures.png.

I found this answer https://gamedev.stackexchange.com/questions/38451/repeat-a-part-of-spritesheet-as-background but I am not sure what the accepted answer is referring to with the generatePattern() method, as far as I can tell this isn't even a canvas method.

Thanks in advance!


Solution

  • Okay I've worked out the solution to this. Basically, createPattern() can take either an image or canvas element as its first argument. So you need to do the following:

    var pattern_canvas = document.createElement('canvas');
    
    pattern_canvas.width = texture_width;
    pattern_canvas.height = texture_height;
    
    var pattern_context = pattern_canvas.getContext('2d');
    
    pattern_context.drawImage(img , texture_sx , texture_sy , texture_width , texture_height);
    
    var final_pattern = canvas_context.createPattern(pattern_canvas , "repeat");
    
    canvas_context.fillStyle = final_pattern;
    canvas_context.fillRect( 0 , 0 , canvas.width , canvas.height );
    

    If you do this then your canvas element will have pattern_canvas repeatedly drawn to cover its dimensions.