Wednesday, January 21, 2026

How to create an image with random number and random alphabets with Javascripts

HTML

 <body>

    <canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">

        Your browser does not support the HTML5 canvas tag.

    </canvas>

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

</body>


JAVASCRIPT

function generateRandomLetters(length) {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
}

// Example usage to get a 6-letter string:
const randomLetters = generateRandomLetters(6);


// Get the canvas element and its 2D context
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

// Draw a rectangle
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, 150, 75);

// Draw some text
ctx.font = "30px Arial";
ctx.fillStyle = "#000000";
ctx.fillText(randomLetters, 10, 50);

// Optional: Convert canvas content to an image data URL
const imageDataUrl = canvas.toDataURL("image/png");
console.log(imageDataUrl); // You can use this URL as the src for a new <img> element
document.write(randomLetters);

OR

// Get the canvas element and its 2D context
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

// Draw a rectangle
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, 150, 75);

// Draw some text
ctx.font = "30px Arial";
ctx.fillStyle = "#000000";
ctx.fillText(Math.random(), 10, 50);

// Optional: Convert canvas content to an image data URL
const imageDataUrl = canvas.toDataURL("image/png");
console.log(imageDataUrl); // You can use this URL as the src for a new <img> element
document.write(Math.random());


No comments:

Post a Comment