Using a sprite sheet with createPattern()

烂漫一生 提交于 2019-12-10 18:14:20

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/21084169/using-a-sprite-sheet-with-createpattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!