我很难在HTML5画布的2d上下文中渲染几个模式(每个模式都有不同的纹理)。
假设我有三个独立的画布,两个屏幕外包含不同的纹理,一个用于渲染。让这些离线画布分别为A和B。
然后:
var patternA = ctx.createPattern(A, "repeat-x");
ctx.fillStyle = patternA;
ctx.fillRect(100,100,20,20);
var patternB = ctx.createPattern(B, "repeat-y");
ctx.fillStyle = patternB;
ctx.fillRect(150,100,20,20);
应该有两个20x20的矩形,每个都有自己的模式,但是第二个矩形根本不渲染。我想尽一切办法让它们工作,但都没有用。
为什么会这样呢?如何在同一画布上渲染多个平铺纹理?
发布于 2012-01-07 03:46:39
你在尝试什么浏览器?在使用FireFox和Chrome时,我无法使用repeat-x
或repeat-y
渲染这两种模式。取而代之的是,我只用repeat
就能让两者都呈现出来。(参见http://jsfiddle.net/ZthsS/1/)
浏览器可能对该规范的实现不完整。根据http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-createpattern的实现情况,IE测试版和FF每晚都能通过所有测试用例,但其他浏览器不能。我建议暂时还是使用repeat
。您可以通过简单地将fillRect的宽度限制为模式的宽度来模拟repeat-x
和repeat-y
:
var patternA = ctx.createPattern(A, "repeat");
ctx.fillStyle = patternA;
ctx.fillRect(100,100,20,Math.min(20, A.height));
var patternB = ctx.createPattern(B, "repeat");
ctx.fillStyle = patternB;
ctx.fillRect(150,100,Math.min(20, B.width), 20);
https://stackoverflow.com/questions/8761670
复制相似问题