我正在尝试绘制位于图像顶部的图表。一旦我删除了背景中的图片,条形图和文本就会完美显示。我无法弄清楚如何使条形图和文字位于图像的顶部。任何帮助将不胜感激。谢谢你
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>
答案 0 :(得分:1)
您正在延迟图像的绘制,直到它被异步加载,但您仍在立即绘制条形图和文本。 这导致图像被绘制在条形和文本之上。 只需将调用移动到将图形和条形图绘制到图像的加载事件中,就可以解决问题。
答案 1 :(得分:0)
如果您已准备好离开JS执行此特定任务,那么您可以使用PHP,特别是GD库来完成此操作。然后,您可以通过简单地循环浏览图像来创建一个cronjob来为您刷新这些内容。
请参阅:http://www.php.net/manual/en/book.image.php
我之前使用GD库作为服务器列表网站。我能够为每台服务器生成一个品牌横幅,显示在线玩家数量,正常运行时间和其他统计数据。
上面提到的PHP官方网站上有一些很好的例子。我很欣赏这种反应并没有直接帮助 - 但希望这是一种见解。祝你好运!
答案 2 :(得分:0)
您的图片需要花费一些时间来加载,这可能导致它最后加载而不是首先加载。我建议将其他两个绘图函数包装在事件监听器中。
img.addEventListener('load', function(){
ctx.drawImage(img, 0, 0, 400, 300);
drawBars();
drawCharText();
},
false);