Javascript ile Rastgele Renk Oluşturucu

JavaScript ile bir rastgele RGB renk oluşturucu kodu için aşağıdaki örneği kullanabilirsiniz. Butona her tıklandığında yeni bir renk oluşturulur.


<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rastgele Renk Oluşturucu</title>
    <style>
        body {
            text-align: center;
            padding-top: 50px;
        }
        .color-box {
            width: 200px;
            height: 200px;
            margin: 0 auto;
            border: 2px solid black;
        }
        button {
            margin-top: 20px;
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="color-box" id="color-box"></div>
    <button onclick="changeColor()">Renk Değiştir</button>

    <script src="script.js"></script>
</body>
</html>

JavaScript (script.js):


function randomColor() {
    // Rastgele RGB değerleri oluştur
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);

    // RGB değerlerini birleştirerek renk kodunu oluştur
    var color = "rgb(" + r + ", " + g + ", " + b + ")";

    return color;
}

function changeColor() {
    var colorBox = document.getElementById("color-box");
    colorBox.style.backgroundColor = randomColor();
}


Bu kod, bir HTML dosyasında bir butona tıklandığında rastgele bir renk oluşturur ve bu rengi bir kutunun arka plan rengi olarak ayarlar. changeColor fonksiyonu butona tıklandığında çağrılır ve arka plan rengini rastgele oluşturulan renge ayarlar.