Reputation: 9
I am trying to draw a chart that sits on top of an image. Once I remove the picture in the background the bars and text display perfectly. I cannot figure out how to get the bars and text to sit on top to the image. Any help would be greatly appreciated. Thanks you
js:
(function(){
var canvas = document.createElement('canvas');
canvas.width = 400;
canvas.height = 300;
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = 'images/bg.jpg';
img.addEventListener('load', function(){
ctx.drawImage(img, 0, 0, 400, 300);
},
false);
var charData = [Math.floor(Math.random()* 100), Math.floor(Math.random()* 100), Math.floor(Math.random()* 100), Math.floor(Math.random()* 100)];
//console.log(charData);
var maxBarHeight = 200;
var drawBars = function(){
ctx.font = '14px Georgia';
for(i=0; i<charData.length; i++){
ctx.beginPath();
ctx.fillStyle ='rgba(100, 200, 200, 0.75)';
var height = maxBarHeight*charData[i]/100;
ctx.height = height;
ctx.rect(i*80+90,270-height,50,height);
ctx.fill();
ctx.font.fillStyle ='rgb(255,255,255)';
ctx.fillText(charData[0], 100,50);
ctx.fillText(charData[1], 180,50);
ctx.fillText(charData[2], 265,50);
ctx.fillText(charData[3], 350,50);
}
};
var drawCharText = function(){
console.log("in draw text");
ctx.font = '20px Georgia';
ctx.fillStyle = 'rgb(0,0,255)';
ctx.fillText('TEST GRADS', 30,30);
};
drawBars();
drawCharText();
})();
html:
<!DOCTYPE html>
<html>
<head>
<title>Goal9: Assignment: Canvas</title>
</head>
<body>
<script src="js/main.js"></script>
</body>
</html>
Upvotes: 0
Views: 360
Reputation: 1
Your image is taking a moment to load which may cause it to load last and not first. I would suggest wrapping your other two draw functions inside your event listener.
img.addEventListener('load', function(){
ctx.drawImage(img, 0, 0, 400, 300);
drawBars();
drawCharText();
},
false);
Upvotes: 0
Reputation: 703
You are delaying the drawing of the image untill after it has been loaded asyncronously, but you are still drawing the bars and text immediately. This results in the image being drawn on top of the bars and text. Simply move the call to drawing the text and bars into the load event for the image and your problem should be solved.
Upvotes: 1
Reputation: 504
If you're prepared to walk away from JS for this particular task, then you can do it using PHP, specifically the GD Library. You could then create a cronjob to refresh these for you by simply cycling through the images.
See: http://www.php.net/manual/en/book.image.php
I have used the GD library previously for a server listing website. I was able to produce a branded banner for each server displaying the number of players online, the uptime and other statistics.
There are some great examples on the PHP official website liked above. I appreciate that this response isn't directly helpful - but hopefully it's an insight. Good luck!
Upvotes: 0