[英]Function undefined for onclick event -HTML5 canvas
I'm just starting out working with the HTML5 canvas and I want to use onclick
to call as js
function in my document. 我刚开始使用HTML5画布,我想在文档中使用
onclick
作为js
函数进行调用。
However, despite declaring the function in my JS, I still get [function name] is not defined
when clicking. 但是,尽管在我的JS中声明了该函数,但单击时
[function name] is not defined
。
The function is defined as such: 该函数的定义如下:
function draw_b() {
var b_canvas = document.getElementById("b"); // finds the canvas in the DOM
var b_context = b_canvas.getContext("2d"); // context for drawing. No 3D option yet
b_context.fillRect(50, 25, 150, 100);
}
The click event is included as such: 单击事件包括如下:
onclick="draw_b();return false"
Yet when I click the element, I get: 但是,当我单击该元素时,我得到:
draw_b is not defined
In JSfiddle you need to use the No Wrap - In <head>
option so the function is defined when used inline for the HTML elements. 在JSfiddle中,您需要使用
No Wrap - In <head>
选项,以便在将内联用于HTML元素时定义该函数。 Also var b_canvas = document.getElementById("b");
另外
var b_canvas = document.getElementById("b");
should be var b_canvas = document.getElementById("a");
应该是
var b_canvas = document.getElementById("a");
您使用了错误的ID
var b_canvas = document.getElementById("a");// Use `a` not `b`
Jsfiddle doesn't like onclick=""
so you need to use addEventListener
from JavaScript. Jsfiddle不喜欢
onclick=""
因此您需要使用JavaScript中的addEventListener
。
var a_canvas = document.getElementById("a"); a_canvas.addEventListener("click",draw_b); function draw_b() { var b_canvas = document.getElementById("b"); // finds the canvas in the DOM var b_context = b_canvas.getContext("2d"); // context for drawing. No 3D option yet b_context.fillRect(50, 25, 150, 100); }
canvas { border: 1px dotted; }
<canvas id="a" width="300" height="225"></canvas> <canvas id="b" width="300" height="225"></canvas>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.