1

I'm just starting out working with the HTML5 canvas and I want to use onclick to call as js function in my document.

However, despite declaring the function in my JS, I still get [function name] is not defined when clicking.

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

JSFiddle

1
  • You want to use No Wrap - In Head in jsFiddle. Also what is document.getElementById("b"), where is it defined? Maybe you mean a? Commented Oct 14, 2015 at 17:54

3 Answers 3

3

In JSfiddle you need to use the No Wrap - In <head> option so the function is defined when used inline for the HTML elements. Also var b_canvas = document.getElementById("b"); should be var b_canvas = document.getElementById("a");

jsFiddle

Sign up to request clarification or add additional context in comments.

Comments

0

You are using the wrong ID

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

Comments

-1

Jsfiddle doesn't like onclick="" so you need to use addEventListener from JavaScript.

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.