I am new at creating applications using jQuery but I am quite familiar with Javascript. Well, what I am trying to do is use the Javascript getElementById in order to draw an image in html5 canvas. My code is:
Include the jQuery and JQuery mobile:
<link rel="stylesheet" type="text/css" href="lib/jquery.mobile-1.0b1.min.css" />
<script type="text/javascript" src="lib/jquery-1.6.1.js"></script>
<script type="text/javascript" src="lib/jquery.mobile-1.0b1.min.js"></script>
The code with problem:
<div data-role="content">
<!--//TO DO canvas drawing-->
<canvas id="draw_area" width="295px" height = "390px"></canvas>
...
<script type="text/javascript">
var canvas = getElementById("draw_area");
var context = canvas.getContext('2d');
var map = new Image();
map.src = "./imgs/home_screen1.png";
map.onload = function (){
context.drawImage (map, 0, 0);
};
</script>
I also noticed that I am not able to use the
<body onload = "aFunction();">
not any other Javascript event like “onclick”.
Am I doing something wrong?
That should be:
Your script is running the
getElementByIdline as soon as it is loaded, which is failing (due to the missingdocument.) and preventing the scripts on the rest of your page from executing.Here’s a quick demo to show you how script errors will prevent subsequent lines from executing.
Once that’s fixed, as @swalk says, you should encapsulate that script so it runs on
document.readyto keep things tidy.