5

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!

Community
  • 1
  • 1
Rohan Deshpande
  • 694
  • 8
  • 22

1 Answers1

4

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.

Rohan Deshpande
  • 694
  • 8
  • 22
  • In the 5-argument version of the [drawImage function](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage), the second two arguments indicate the shift in the _output_ image. To select the correct part of the input spritesheet, the drawImage call should use the 9-argument version: `pattern_context.drawImage(img, texture_sx, texture_sy, texture_width, texture_height, 0, 0, texture_width, texture_height);` – Jeshurun Hembd Dec 10 '19 at 01:04