带有不同颜色JavaScript的矩阵
我需要构建2D矩阵50x50代表带有随机颜色的框,但是如果彼此靠近的盒子具有相同的颜色,它们应该彼此获得不同的随机颜色,直到它不同并继续构建。
在这里,我制作了带有盒子的矩阵,它可以正常工作,但是颜色有时确实匹配:
function onLoad(evt)
{
var matrix = [];
for (var i = 0; i < 50; i++) {
var row = [];
for (var j = 0; j < 50; j++) {
var randColor = Math.floor(Math.random()*16777215).toString(16);
row.push(MyComponent(randColor));
}
matrix.push(row);
}
var newData = matrix.map(function(row) {
return row.map(function(x) {
return x;
})})
}
I need to build 2d matrix 50x50 representing boxes with random colors, but if the boxes which are close to each other have the same colors, they should get different random color from each other, until it's different and then continue building.
Here I made matrix with boxes inside it works fine, but colors sometimes do match:
function onLoad(evt)
{
var matrix = [];
for (var i = 0; i < 50; i++) {
var row = [];
for (var j = 0; j < 50; j++) {
var randColor = Math.floor(Math.random()*16777215).toString(16);
row.push(MyComponent(randColor));
}
matrix.push(row);
}
var newData = matrix.map(function(row) {
return row.map(function(x) {
return x;
})})
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要一种方法来确定特定颜色是否离另一种颜色太近。一种方法是用 rgb-lab (或者,不太准确,欧几里得距离)。假设您使用RGB-LAB的
deltae
函数,该函数需要两个参数,其中每个参数是RGB量的3个项目数组。生成随机颜色,以便您可以轻松获取其组件的小数值,并可以轻松获得他们的十六进制字符串表示形式。然后迭代相邻的填充指示并比较颜色。如果它们太相似,请重试。按照:
根据需要更改最小值距离的内容。请参阅在这里以说明数字。
然后,您需要将颜色对象变成带有颜色字符串的组件阵列。
You need a way to determine whether a particular color is too close to another. One way to do this is with rgb-lab (or, less accurately, euclidean distance). Say you use rgb-lab's
deltaE
function, which takes two arguments, where each argument is a 3-item array of RGB amounts.Generate your random colors such that you can get their components' decimal values easily, and so that you can also get their hex string representation easily. Then iterate over the filled adjacent indicies and compare the colors. If they're too similar, try again. Something along the lines of:
Change the MINIMUM_DISTANCE as desired. See here for an explanation of the numbers.
Then you'll need to turn the color objects into an array of components with color strings at the end.