Reputation: 177
I am trying to draw an image to an Html5 Canvas to be used withing Phonegap, this is the code i used.
the problem is nothing happens i tried almost everything, added the image.onload, tried clearrect still nothing is drawn.
I am using Phonegap 2.7, testing on Android 2.3.7 (GingerBread).
var canvas = document.getElementById('map');
var ctx = canvas.getContext("2d");
var image = new Image();
image.src="img/map-04.png";
image.onload=function(){
ctx.drawImage(image,0,0);
};
function fitToContainer(canvas){
var div = $(mapcontext);
canvas.style.width=div.css("width");
canvas.style.height=div.css("height");
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
}
window.onload = fitToContainer(canvas);
window.onresize = fitToContainer(canvas);
Thanks in Advance.
Upvotes: 2
Views: 8710
Reputation:
Update
Based on the provided fiddle:
You will be able to solve the problem by reorganizing the code a bit by doing:
The updated code looks like this (online live version here):
var canvas = document.getElementById('map');
var ctx = canvas.getContext("2d");
var image = new Image();
image.onload = function() {
window.onresize = fitToContainer;
fitToContainer();
};
image.src = "http://i.imgur.com/oPt1Nrr.gif";
function fitToContainer() {
var div = $('#mapcontext'),
w = $(window).width(),
h = $(window).height();
canvas.width = w;
canvas.height = h;
ctx.drawImage(image, 0, 0, w, h);
}
Hope this helps!
Old answer
The usage of window.onload
or window.onresize
are wrong. You need to pass them references:
window.onload = window.onresize = function() {fitToContainer(canvas)};
You could optionally obtain the canvas element within the function callback and simply call a parameterless function
window.onload = window.onresize = fitToContainer;
function fitToContainer() { ... } // use global var for canvas
Also note that resizing canvas will cause it to be cleared so you'll need to redraw the image when this happens:
function fitToContainer(canvas){
var div = $(mapcontext);
canvas.style.width=div.css("width");
canvas.style.height=div.css("height");
canvas.width = canvas.offsetWidth; // this will clear canvas
canvas.height = canvas.offsetHeight;
if (image && image.complete)
ctx.drawImage(image, 0, 0); // redraw image if loaded
}
You should also add an onerror
handler (and optimally onabort
) for the image in case the error occur during the loading and decoding process. Also add those callbacks before setting src
.
Upvotes: 3