html5里的repeat,javascript - HTML5 Canvas - Repeat Canvas Element as a Pattern - Stack Overflow

You can get the base64 version of your image using the toDataURL() method of the canvas element.

From there it's as simple as setting the background-image of your page to the string "url(" + base64 + ")"

$(document).ready(function(){

var canvas = document.getElementById('dkBg');

var ctx = canvas.getContext('2d');

ctx.canvas.width = 64; //window.innerWidth;

ctx.canvas.height = 64; //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);

}

}

document.documentElement.style.backgroundImage =

'url(' +canvas.toDataURL() + ')';

});

Note that you need to make the canvas 64x64 because that's the size of your source image.

You can also now make the canvas display:none, or even remove it from the dom completely because it's only acting as a source for the background-image.

Also, what on earth is up with those while loops?

while(rand<20){

rand = Math.floor(Math.random()*50);

}

It looks like you're trying to enforce a minimum value. Just use this:

rand = Math.floor(Math.random() * (50-20) + 20);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值