1

In this code :

var canvas = $("#myCanvas")[0];
var ctx = canvas.getContext("2d");

Why do we have to add [0] to identify the canvas? It's a bit confusing for me, because [n] is usually added when there are multiple elements with the same name and we need to address a particular one. But an id can only refer to one unique element.

Magicprog.fr
  • 4,072
  • 4
  • 26
  • 35
  • 3
    jQuery selectors can return multiple objects, so they always return something that looks like an array. IMHO, better just to use `canvas = document.getElementById('myCanvas')` – Alnitak Jan 13 '16 at 10:27
  • 1
    ... or `document.querySelector("#myCanvas")` if you need more complex selectors. – Oriol Jan 13 '16 at 10:31
  • because to use javascript methods like getContext() you need to return the actual dom element and not the jQuery array. For example, doing $("body").innerHTML will give you undefined but $("body")[0].innerHTML will return the contents of body. – gothical Jan 13 '16 at 10:55

2 Answers2

3

This syntax is used to retrieve the underlying canvas DOMElement from the jQuery object so that the getContext() method (which the jQuery object does not have) can be used.

$('#myCanvas')                      // = canvas DOMElement wrapped in a jQuery object
$('#myCanvas')[0]                   // = canvas DOMElement
document.getElementById('myCanvas') // = canvas DOMElement

See also:

What is a jQuery object

canvas API reference

Community
  • 1
  • 1
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

jQuery always returns an array-like object, even if you use a (unique) id as the selector.

In your case the [0] is to return the first (and only) actual element.

Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • @Oriol - yes, I knew that. It was a case of typing too quickly before brain was engaged. Thanks for pointing out my mistake – Jamiec Jan 13 '16 at 10:38