onclick事件-HTML5画布的函数未定义

时间:2015-10-14 17:53:03

标签: javascript html5 canvas

我刚刚开始使用HTML5画布,我想使用onclick在我的文档中调用js函数。

然而,尽管在我的JS中声明了该功能,但在点击时仍然会得到[function name] is not defined

该功能定义如下:

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

点击事件包含在内:

onclick="draw_b();return false"

然而,当我点击元素时,我得到:

draw_b is not defined

JSFiddle

3 个答案:

答案 0 :(得分:3)

在JSfiddle中,您需要使用var b_canvas = document.getElementById("b");选项,以便在内联HTML元素时定义函数。 var b_canvas = document.getElementById("a");也应为display

jsFiddle

答案 1 :(得分:0)

您使用了错误的ID

var b_canvas = document.getElementById("a");// Use `a` not `b`

答案 2 :(得分:-1)

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>
&#13;
&#13;
&#13;