This is more of a jquery question than an html5 question, but a good example non-the-less.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
context = $("#mainCanvas")[0].getContext("2d");
alert(context);
context.fillStyle = "rgb(200,0,0)";
context.fillRect (10, 10, 55, 50);
context.fillStyle = "rgba(0, 0, 200, 0.5)";
context.fillRect (30, 30, 55, 50);
});
</script>
</head>
<body>
<canvas id="mainCanvas" width="800" height="600">
</canvas>
</body>
</html>
In order to call the “getContext” function on the canvas object, I have to index into the jquery object like so:
$("#mainCanvas")[0].getContext("2d")
Needing to index into the object is clunky and not intuitive. My question is, is there not a way for jquery to infer that a “missing” function on the jquery object would be contained within the wrapped object automatically? Is there some jquery syntax trick that I am missing?
Thanks.
There is no way to override a call to a missing Javascript method that I am aware of. It’s a shame too, since I could really use something like that for an issue I’ve been working on lately. The best you can do is some sort of function wrapper, like so:
But that’s not terribly pretty and the performance will be less-than-good. shrug
In your case, though, is this really all that bad? You’re only going to be making the one call and then caching off the graphics context for all the rest of your calls. If the index syntax is really all that offensive to you, going jQuery-less for this call is also a cleaner option:
That’s also going to be a smidge faster, if you care about such things. Really, jQuery provides pretty much nothing when it comes to canvas manipulation.