簡體   English   中英

未定義onclick事件的函數-HTML5 canvas

[英]Function undefined for onclick event -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

在JSfiddle中,您需要使用No Wrap - In <head>選項,以便在將內聯用於HTML元素時定義該函數。 另外var b_canvas = document.getElementById("b"); 應該是var b_canvas = document.getElementById("a");

的jsfiddle

您使用了錯誤的ID

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

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM