使用 JavaScript 将图像加载到画布上

新手上路,请多包涵

我目前正在测试使用 <canvas> 元素来绘制所有背景(稍后我会为这些图像添加效果,这也是我不使用 CSS 加载图像的原因)。也就是说,我目前很难将图像加载到画布上。这是代码:

 <html>
<head>
    <title>Canvas image testing</title>
    <script type="text/javascript">
        function Test1() {
            var ctx = document.getElementById('canvas');
            if (canvas.getContext) {
                var ctx = canvas.getContext('2d');
                //Loading of the home test image - img1
                var img1 = new Image();
                img1.src = 'img/Home.jpg';
                //drawing of the test image - img1
                img1.onload = function () {
                    //draw background image
                    ctx.drawimage(img1, 0, 0);
                    //draw a box over the top
                    ctx.fillStyle = "rgba(200, 0, 0, 0.5)";
                    ctx.fillRect(0, 0, 500, 500);
                };
            }
        }
    </script>
    <style type="text/css">
        canvas { border: 2px solid black; width: 100%; height: 98%; }
    </style>
</head>
<body onload="Test1();">
    <canvas id="canvas" width="1280" height="720"></canvas>
</body>
</html>

我认为我没有正确加载图像,但我不确定。

原文由 dee Five 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 227
1 个回答

有几件事:

  1. drawimage 应该是 drawImage 注意大写i。
  2. 您的 getElementById 正在寻找 ID 为 canvas 的元素,但它应该是 test1canvas 是标签,不是 ID。
  3. canvas 变量(例如在您的 canvas.getContext 行中)替换为 ctx ,因为这是您用来选择画布元素的变量。
  4. 在设置图像的 src 之前绑定您的 onload 处理程序。

所以你的函数应该像这样结束:

 function Test1() {
    var ctx = document.getElementById('test1');
    if (ctx.getContext) {

        ctx = ctx.getContext('2d');

        //Loading of the home test image - img1
        var img1 = new Image();

        //drawing of the test image - img1
        img1.onload = function () {
            //draw background image
            ctx.drawImage(img1, 0, 0);
            //draw a box over the top
            ctx.fillStyle = "rgba(200, 0, 0, 0.5)";
            ctx.fillRect(0, 0, 500, 500);

        };

        img1.src = 'img/Home.jpg';
    }
}

原文由 freejosh 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题