Doudoumoumou
Doudoumoumou

Reputation: 1

Set image random width and height in javascript

I wrote this script that choose a random bird family, and everytime you click the canvas it place an image of the bird type at a random place on the canvas. I want to make it so the size of the bird image is random.


<script>
            //Récupérer la balise canvas et définir son contexte de dessin en 2d
            let leCanvas = document.querySelector("canvas");
            let ctx = leCanvas.getContext("2d");

            //Affichage de l'image d'arrière-plan (élément HTML <img>)
            leCanvas.style.backgroundImage = "url('images/paysage.png')";

            //Variable pour l'image d'un oiseau (élément HTML <img>)
            let img = new Image();

            //Variable pour choisir un oiseau au hasard parmi les 5 disponibles
            let choixOiseau = Math.ceil(Math.random()*5)

            /*Charger l'image de l'oiseau
             * Note ici on a pas besoin de surveiller le chargement avec l'événement load
             * car l'image sera dessinée uniquement quans l'utilisateur va cliquer dans le <canvas>
             */
            img.src = "images/oiseau"+choixOiseau+".png";

            //Afficher le texte pour indiquer la famille d"oiseau
                leCanvas.addEventListener("click", afficherTexte);

            /*Gestionnaires d'événement
             * un clic permet de dessiner au hasard un oiseau dans le <canvas>
             * un double clic permet d'effacer tous les oiseaux
             */
            leCanvas.addEventListener("click", dessinOiseau);
            leCanvas.addEventListener('dblclick', effacerOiseau);

            /*Randomize image size*/
            let facteur = Math.ceil(Math.random() * (100 - 30) + 30)
            let width = img.width*facteur;
            let height = img.height*facteur;

            //Fonction pour afficher le texte indiquant la famille d'oiseau
            function afficherTexte() {
                //Style du texte
                ctx.font = "bold 48px Tahoma";
                ctx.textAlign = "right";
                ctx.textBaseline = "bottom";
                ctx.fillStyle = "white";

                //Dessiner le texte en bas et à droite du canvas
                ctx.fillText = ("Famille d'oiseaux # "+choixOiseau+"", leCanvas.width/2, leCanvas.height/2);
            }

            //Fonction pour dessiner un oiseau au hasard : dessinerUnOiseau
            function dessinOiseau() {
                let x = Math.random() * (leCanvas.width - img.width);
                let y = Math.random() * (leCanvas.height - img.height);
                ctx.drawImage(img, x, y)
            }

            //Fonction pour effacer tous les oiseaux dessinés : effacerLesOiseaux
            function effacerOiseau() {
                ctx.clearRect(0, 0, leCanvas.width, leCanvas.height);
            }

            //Fonction pour rendre aléatoire la taille des oiseaux
        </script>

I googled about Math.floor(Math.random() * (max - min) + min) but I don't know how to use it in the dessinerOiseau function. I think that the solution have something to do with "width" and "height" variable, something like this:

width = Math.random().floor() * min height = Math.random().floor() * min

please help me figure this out :D

Upvotes: 0

Views: 333

Answers (1)

IT goldman
IT goldman

Reputation: 19485

Do you want to randomize image to range of 30%..100% and randomize a position?

I'll use a function from mdn, and won't forget to set width and height parameters for drawImage()

function random_int(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1) + min);
}

window.onload = function() {
  var new_size_percent = random_int(30, 100)
  console.log("new size: " + new_size_percent + "%")
  var new_size = image.width * new_size_percent / 100;
  
  var ratio = new_size / image.width;
  var width = image.width * ratio
  var height = image.height * ratio

  var ctx = canvas.getContext("2d");
  ctx.drawImage(image, 0, 0, width, height);

}
<img id="image" src="https://picsum.photos/200/100">
<canvas id="canvas" width="200" height="100"></canvas>

Upvotes: 0

Related Questions