是否可以使用图像而不是颜色来“填充” HTML5 画布上的形状?
我画了一堆形状(各个角以 45 度角切掉的正方形)。我希望能够用图像而不是颜色来“填充”这些形状。目前我有一行指出:
context.fillStyle = '#123456' // example fill color
我正在寻找的是这样的:
context.fillStyle = 'url(http://www.myimagereference.com/image.png)';
我知道我不能以这种方式使用 fillStyle - 但是还有其他方法可以实现这种事情吗?
你可能想看看创建模式 http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-createpattern
下面是一个简单的代码,演示了如何使用创建模式
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var w = canvas.width = 256;
var h = canvas.height = 256;
var img = new Image();
img.src = "http://www.gravatar.com/avatar/e555bd971bc2f4910893cd5b785c30ff?s=128&d=identicon&r=PG";
img.onload = function () {
var pattern = ctx.createPattern(img, "repeat");
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, w, h);
};
尝试一个例子 http://jsfiddle.net/36vfdx27/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)