My goal is to generate a random “realistic” planet with JavaScript. The problem i have is to make it look good and not just random colors. My current script takes colors between 2 random generated colors and fills the sphere with a random color between the 2 values.
My goal is to have something that looks close(er) to this
I made that image in Photoshop and yes I know I cant get anywhere close to that result in a easy way, but I want to improve the code in anyway so it looks better. And I dont know how to proceed, any ideas on how to improve is helpful.
var colors;
window.onload = function () {
generatePlanet();
}
function generatePlanet() {
colors = interpolateColors("rgb(" + getRndColor() + "," + getRndColor() + "," + getRndColor() + ")", "rgb(" + getRndColor() + "," + getRndColor() + "," + getRndColor() + ")", 6000);
drawPlanet()
}
function getRndColor() {
return Math.floor(Math.random() * 256)
}
function interpolateColors(color1, color2, steps) {
var stepFactor = 1 / (steps - 1),
interpolatedColorArray = [];
color1 = color1.match(/d+/g).map(Number);
color2 = color2.match(/d+/g).map(Number);
for (var i = 0; i < steps; i++) {
interpolatedColorArray.push(interpolateColor(color1, color2, stepFactor * i));
}
return interpolatedColorArray;
}
function interpolateColor(color1, color2, factor) {
if (arguments.length < 3) {
factor = 0.5;
}
var result = color1.slice();
for (var i = 0; i < 3; i++) {
result[i] = Math.round(result[i] + factor * (color2[i] - color1[i]));
}
return result;
};
function drawPlanet() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var i = 0, j = 0;
function animate() {
ctx.beginPath();
ctx.fillRect(10 * j, 10 * i, 10, 10);
ctx.fillStyle = 'rgb(' + colors[Math.floor(Math.random() * 6001)] + ')';
ctx.fill();
ctx.closePath();
j += 1;
if (j >= 70) {
i += 1;
j = 0;
}
if (i < 70) {
animate();
}
}
animate();
}
#canvas {
border: 10px solid #000000;
border-radius: 50%;
}
<button onclick="generatePlanet()">GENERATE</button>
<canvas id="canvas" width="700" height="700"></canvas>
2
Answers
There is comments in the code if you are interested in a random generated planet. I have not set any color restrictions so some color matches looks a little weird. If something is unclear just ask with a comment.
It’s can be more complex task then is looks like. But I can suggest you use next two step way to do it