Reputation: 22366
This code displays a picture in a Canvas:
<!DOCTYPE html>
<html><head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type"><title>canpic</title>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache"><META HTTP-EQUIV="Expires" CONTENT="-1">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<style>
canvas { border: 42px solid green; }
</style>
</head><body>
CANVAS PICTURE TEST
<br>
<canvas id="pinaka" width="600" height="370">
No HTML5 in this browser!
</canvas>
<br>
<p id="message"></p>
<script>
var can; // Canvas
var ctx; // Canvas context
var backimage=new Image();
function test1() {
can=document.getElementById("pinaka");
ctx=can.getContext('2d');
backimage.src="images/p1.jpg";
alert('drawing');
ctx.drawImage(backimage,0,0);
}
$(document).ready(function() { test1(); })
</script>
</body></html>
This works well on several browsers I tried, with one exception:
When I first load this page on Safari 4, the picture is drawn well, but when I do a page reload (Apple-R key), only the canvas border is drawn, but the interior of the canvas stays blank. There is also no error shown in the error console. I could verify that my function test1() has been called after the reload, because the alert box shows up.
Is this just a bug in Safari 4, which I have to accept, or is there a problem with my code? At least with two other browsers tried (Camino and SeaMonkey), the code works well.
Upvotes: 0
Views: 101
Reputation: 22366
I modified my function in th following way:
function test1() {
can=document.getElementById("pinaka");
ctx=can.getContext('2d');
backimage.onload = function() {
ctx.drawImage(backimage,0,0);
}
backimage.src="images/p1.jpg"; // triggers loading the picture
}
Now it works (because it is ensured that the picture is loaded before drawing begins.
Upvotes: 1