我有一个非常奇怪的例子......我需要填充一个1x1像素的圆圈,所有这些都在浏览器中使用不同的颜色.
我试过的是这样的
function getRandomColor() { var letters = '0123456789ABCDEF'.split(''); var color = '#'; for (var i = 0; i < 6; i++ ) { color += letters[Math.round(Math.random() * 15)]; } return color; } function createRandomSqaure(destination) { var size = destination.height() * destination.width(); for (var i = 0; i < size; i += 1) { destination.append(''); } } createRandomSqaure($('.pic'));
情况是,它超级慢(你可以想象,200x200图像的循环次数为40k),我想也许更好的方法是在画布上绘制它?我需要在最后绘制一个充满这些像素的圆圈......
我不知道如何以更优化的方式做这样的事情,我也可以使用nodejs服务器,但我认为在heroku上生成类似服务器端的东西太过分了.
我只是好奇你们有什么想法,做这样的事情最好的方法是什么?
你可以使用这样一个简单的方法:
在画布上以200x200网格绘制具有随机颜色的所有像素
改变复合模式
在上面画圆圈
结果是:
例:
var canvas = document.getElementById('canvas'), // get canvas element ctx = canvas.getContext('2d'), // get context x, y = 0, // initialize dia = canvas.width, radius = dia * 0.5; ctx.translate(0.5, 0.5); // to make pixels sharper for(; y < dia; y++) { // walk x/y grid for(x = 0; x < dia; x++) { ctx.fillStyle = getRndColor(); // set random color ctx.fillRect(x, y, 1, 1); // draw a pixel } } // create circle // removes pixels outside next shape ctx.globalCompositeOperation = 'destination-in'; ctx.arc(radius, radius, radius, 0, 2*Math.PI); ctx.fill(); // reset ctx.globalCompositeOperation = 'source-over'; function getRndColor() { var r = 255*Math.random()|0, g = 255*Math.random()|0, b = 255*Math.random()|0; return 'rgb(' + r + ',' + g + ',' + b + ')'; }