我有一个 64x64 Canvas 方形元素,我想在 x 和 y 方向上重复它以填充页面。我找到了很多关于如何使用图像执行此操作的解释,但没有一个解释如何使用 canvas 元素执行此操作。到目前为止,这是我的代码:
$(document).ready(function(){
var canvas = document.getElementById('dkBg');
var ctx = canvas.getContext('2d');
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
ctx.fillStyle = 'rgb(0,0,0)';
//I want the following rectangle to be repeated:
ctx.fillRect(0,0,64,64);
for(var w=0; w<=64; w++){
for(var h=0; h<=64; h++){
rand = Math.floor(Math.random()*50);
while(rand<20){
rand = Math.floor(Math.random()*50);
}
opacity = Math.random();
while(opacity<0.5){
opacity = Math.random();
}
ctx.fillStyle= 'rgba('+rand+','+rand+','+rand+','+opacity+')';
ctx.fillRect(w,h,1,1);
}
}
});
问题是,我不希望重新生成所有随机数/等等。我只想平铺完全相同的正方形以适合页面。这可能吗?
这是一个 fiddle :http://jsfiddle.net/ecMDq/
最佳答案
做自己想做的事其实 super 简单。您根本不需要使用图片。 createPattern 函数接受图像或另一个 Canvas ! (或者视频标签,甚至)
您所要做的就是制作一个只有 64x64 大的 Canvas 并在其上制作图案。我们称此 Canvas 为 pattern
。您只需设计一次。
然后在主 Canvas 的上下文中我们可以做:
// "pattern" is our 64x64 canvas, see code in fiddle
var pattern = ctx.createPattern(pattern, "repeat");
ctx.fillStyle = pattern;
使用您的代码制作图案,然后将其重复到 500x500 Canvas 上的工作示例:
关于javascript - HTML5 Canvas - 重复 Canvas 元素作为模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9101613/