我正在尝试将 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/