Search code examples
javascriptimagecanvaspngquery-string

JavaScript file with query string to dynamically generate canvas as a png image in img src


I have a JavaScript that renders a drawing on canvas taking into account three given variables. I would like it to function as an image that can be referred to externally, i.e. by writing <img src="canvas.js?a=abc&b=def&c=ghi"> within any html file it should generate a PNG image there. Any suggestions?


Solution

  • You should create a function and call it, passing variables that way.

    Here's an example that should help you:

    HTML

    <!-- your generated image will be displayed here -->
    <canvas id="your-canvas" width="800" height="600"></canvas>
    
    <!-- include canvas.js -->
    <script src="canvas.js"></script>
    
    <script>
        // call the function that is defined in canvas.js
        drawImage("abc","def","ghi");
    </script>
    

    canvas.js

    // select the canvas element in your page
    let canvas = document.getElementById("your-canvas");
    let ctx = canvas.getContext("2d");
    
    // define a function that draws inside your selected canvas element
    function drawImage (a, b, c) {
        ctx.font = "30px Arial";
        ctx.fillText(a + b + c, 10, 50);
    }
    

    Edit: I have also noticed that you're trying to output canvas.js to an img element. Unfortunately, that is impossible. Instead you'll need to use a canvas element, like I showed in my example (the output will still be an image).