【问题标题】:JavaScript file with query string to dynamically generate canvas as a png image in img src带有查询字符串的 JavaScript 文件,用于在 img src 中动态生成画布作为 png 图像
【发布时间】:2021-03-31 15:45:35
【问题描述】:

我有一个 JavaScript 可以在 canvas 上渲染一个绘图,并考虑三个给定的变量。我希望它可以用作可以在外部引用的图像,即通过在任何 html 文件中写入 <img src="canvas.js?a=abc&b=def&c=ghi"> 它应该在那里生成一个 PNG 图像。有什么建议吗?

【问题讨论】:

    标签: javascript image canvas png query-string


    【解决方案1】:

    我看到您在问题中使用了 PHP 语法。您不能像在 PHP 中那样将变量传递给 JavaScript。相反,您应该创建一个函数并调用它,以这种方式传递变量。

    这里有一个可以帮助你的例子:

    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);
    }
    

    编辑:我还注意到您正在尝试将 canvas.js 输出到 img 元素。不幸的是,这是不可能的。相反,您需要使用画布元素,就像我在示例中展示的那样(输出仍然是图像)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-31
      • 1970-01-01
      • 2013-03-26
      • 1970-01-01
      • 2013-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多