gpt4 book ai didi

javascript - 在 Canvas 上绘制一个充满随机彩色方 block 的圆

转载 作者:太空狗 更新时间:2023-10-29 15:45:32 24 4
gpt4 key购买 nike

我有一个非常奇怪的例子要处理......我需要用 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('<div class="pixel" style="background: ' + getRandomColor() + '"></div>');
}
}

createRandomSqaure($('.pic'));

情况是,它 super 慢(如您所想,对于 200x200 的图像,循环进行了 40k 次),我想也许更好的方法是在 Canvas 上绘制它?最后我需要画一个充满这个像素的圆...

我不知道如何以更优化的方式做这样的事情,我也可以使用 nodejs 服务器,但我认为在 heroku 上生成类似这个服务器端的东西太过分了。

我很好奇你们怎么想,做这样的事情最好的方法是什么?

最佳答案

您可以使用像这样的简单方法:

  • 在 Canvas 上以 200x200 的网格以随机颜色绘制所有像素
  • 更改复合模式
  • 在上面画圈

Live demo

结果:

enter image description here

示例:

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 + ')';
}

关于javascript - 在 Canvas 上绘制一个充满随机彩色方 block 的圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22237497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com