使用带有createPattern()的精灵表 [英] Using a sprite sheet with createPattern()

查看:133
本文介绍了使用带有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.

我有一个大的精灵表,我们称之为textures.png。每个纹理是64x64像素,我需要能够从这些纹理创建模式。

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()是一个很棒的函数,但似乎只有两个参数,即图像源以及是否重复它。如果你为每个纹理加载一个图像,这很好,但我想知道如何使用textures.png这样做。

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.

我找到了这个答案 https://gamedev.stackexchange.com/questions/38451/repeat-a-part-of-spritesheet-as-background 但我不确定接受的回答是什么引用了generatePattern( )方法,据我所知,这甚至不是画布方法。

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.

提前致谢!

推荐答案

好的,我已经找到了解决方案。基本上,createPattern()可以将image或canvas元素作为其第一个参数。所以你需要做以下事情:

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 );

如果你这样做,那么你的canvas元素将重复绘制pattern_canvas以覆盖它的尺寸。

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

这篇关于使用带有createPattern()的精灵表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆