Javascript 'this' 传递 Canvas 以在页面加载时运行

标签 javascript html canvas this

我正在尝试将 canvas HTML 元素作为参数传递,我认为“this”会起作用,但我不太明白。有人可以帮我使用“this”关键字在页面加载时将 Canvas 传递给 main() 吗?

不起作用:

<html>
    <head>
    <title>Draw on Canvas</title>
    </head>
    <body onload=main(this.firstChild)><canvas></canvas></body>
    <script>
        function main(canv) {
            cntx = canv.getContext("2d");
            cntx.rect(10, 10, 100, 100);
            cntx.fill();
        }
    </script>
</html>

有效,但想改用“this”关键字:

<html>
    <head>
    <title>Draw on Canvas</title>
    </head>
    <body onload=main(document.body.firstChild)><canvas></canvas></body>
    <script>
        function main(canv) {
            cntx = canv.getContext("2d");
            cntx.rect(10, 10, 100, 100);
            cntx.fill();
        }
    </script>
</html>

不起作用(未为 Canvas 元素定义 onload):

<html>
    <head>
    <title>Draw on Canvas</title>
    </head>
    <body><canvas onload=main(this)></canvas></body>
    <script>
        function main(canv) {
            cntx = canv.getContext("2d");
            cntx.rect(10, 10, 100, 100);
            cntx.fill();
        }
    </script>
</html>

有效,并使用“this”,但希望代码在不单击的情况下运行:

<html>
    <head>
    <title>Draw on Canvas</title>
    </head>
    <body><canvas onclick=main(this)></canvas></body>
    <script>
        function main(canv) {
            cntx = canv.getContext("2d");
            cntx.rect(10, 10, 100, 100);
            cntx.fill();
        }
    </script>
</html>

最佳答案

我建议您考虑一种不同的方法,因为如果您将其混合到 HTML 标记中,您可能会冒着使整个脚本逻辑的表现力复杂化的风险。更重要的是,虽然您不能在 HTML 标记上下文中使用 onload 来获取窗口之外的任何 this,但您可以创建定义为在 window.onload 之后以任何方式执行的 JS 函数想要。

您已经在使用 JavaScript 定义您的 Canvas 属性,何不同时在 JS 中创建 Canvas !

您还可以看到如何扩展它以打开您在动态创建/附加更多 Canvas 方面的选项。

如果这对您不起作用,请告诉我这是否是我可以更直接地帮助解决的问题的抽象问题。

<html>
    <head>
        <title>Draw on Canvas</title>
    </head>
    <body>

        <script>
            function createCanvasRect(x, y, width, height) {
                var canv = document.createElement('canvas'),
                    cntx = canv.getContext('2d');

                cntx.rect(x, y, width, height);
                cntx.fill();

                return canv;
            }

            function load() {
                var canvas = createCanvasRect(10, 10, 100, 100);

                document.body.appendChild(canvas);
            }

            window.onload = load;
        </script>
    </body>
    
</html>

关于Javascript 'this' 传递 Canvas 以在页面加载时运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44275506/

相关文章:

javascript - 在 UI 中更改复选框状态时保持不变

javascript - 第一次在 javascript/jquery 中运行函数时没有做任何事情

java - 检查 Thymeleaf 中的 If-Else

html - 如何将 HTML 元素转换为 Canvas 元素?

javascript - 为什么上一张图像会绘制在我的 HTML5 Canvas 上?

Android Force GPU Rendering 如何启用和禁用?

javascript - 如果两个值都会动态更改,则用变量替换某些字符串的一部分 - Javascript

javascript - 谷歌可视化 API : How to format numeric axis labels to time duration?

javascript - 如何正确地将 Javascript 链接到 html 页面

html - 动态展开选中的选项背景