Soulslayer Soulslayer - 1 year ago 120
Javascript Question

image not drawn first time javascript

I know this question has been asked many times. However, I have used img.onload to properly execute what will be drawn to the canvas after the image is loaded. I am new to javascript and having trouble figuring it out. I have done the whole code in a function and calling it from the init() function. This init() function triggers when the body is loaded.

I have two images here. Both of them does not load at the first time.

function getAboutMeImage(){
var galleryCanvas = document.createElement("Canvas");
var galleryContext = galleryCanvas.getContext('2d');
galleryCanvas.width = 800;
galleryCanvas.height = 600; = "absolute"; = "block"; = "50%"; = "50%"; = "-400px"; = "-250px";
// = "#FFF";

var points = [];
points[0] = new Array(0.3,1.3,0.55,1.05,2.9,1.05,3.1,0.75,9.25,0.75,9.9,1.3,9.9,6.3,9.6,6.6,5.75,6.6,5.3,7.0,2.5,7.0,1,4.3,0.3,4.3,0.3,1.3);
var points1 = [];
points1[0] = new Array(3.2,1,9.25,1,9.25,6.4,3.2,6.4,3.2,1);
var y = Math.round((7.0 / 11.0) * galleryCanvas.width);
var width = Math.round(galleryCanvas.width / 11.0);
var height = Math.round(y / 7.0);
var img = new Image();
img.onload = function() {
var canvas2 = document.getElementById("canvas2");
var ctx2 = galleryCanvas.getContext("2d");
ctx2.drawImage(img,0.4 * width, 1.2*height, img.width, img.height);

img.src = "../logo.png";
var ratio = img.height * 1.0/ img.width;
img.width = Math.round(width*2.7);
img.height = Math.round(ratio * img.width);

var img2 = new Image();
img2.src = "../about me background2.png";
var ratio = img2.height * 1.0/ img2.width;
img2.width = Math.round(width*2.8);
img2.height = Math.round(ratio * img.width);
img2.onload = function(){
var ctx3 = galleryCanvas.getContext("2d");
ctx3.drawImage(img2,0.4 * width, 2*height, img2.width, img2.height);


return galleryCanvas.toDataURL();

So, what am I doing wrong?

Answer Source

General advice:

Are both the onload callbacks being triggered?

If not, check the image .src.

Also, check the values you are sending into drawImage.

Are the resulting x,y off the visible canvas area?

Are the resulting width,height zero or near zero?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download