如何在图像上绘制

How to draw on top of an image

本文关键字:绘制 图像      更新时间:2023-09-26

我正在尝试绘制一个位于图像顶部的图表。一旦我删除了背景中的图片,条形图和文本就会完美地显示出来。我不知道如何将条形图和文本放在图像的顶部。如有任何帮助,我们将不胜感激。谢谢

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>

您将延迟绘制图像,直到异步加载图像之后,但仍在立即绘制条形图和文本。这将导致图像绘制在条形图和文本的顶部。只需将绘制文本和条形图的调用移动到图像的加载事件中,您的问题就会得到解决。

如果你准备放弃JS来完成这个特定的任务,那么你可以使用PHP,特别是GD库来完成。然后,您可以创建一个cronjob,通过简单地循环浏览图像来为您刷新这些内容。

请参阅:http://www.php.net/manual/en/book.image.php

我以前在一个服务器列表网站上使用过GD库。我能够为每台服务器制作一个品牌横幅,显示在线玩家的数量、正常运行时间和其他统计数据。

上面有一些PHP官方网站上的好例子。我很感激这种回应没有直接的帮助,但希望这是一种洞察力。祝你好运

您的图像需要一段时间才能加载,这可能会导致它加载到最后而不是第一个。我建议将另外两个draw函数封装在事件监听器中。

        img.addEventListener('load', function(){
            ctx.drawImage(img, 0, 0, 400, 300);
            drawBars();
            drawCharText();
        },
        false);

http://jsfiddle.net/GdtUD/