使用javaScript将图像加载到画布上 [英] Loading an image onto a canvas with javaScript

查看:137
本文介绍了使用javaScript将图像加载到画布上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hi所有目前测试使用画布元素来绘制所有的背景(我会添加效果后来这些图像后,是没有使用CSS加载图像),说我目前有困难将图像加载到画布上。这里是代码:

Hi all im currently testing using the canvas element to draw all of the backgrounds(i will add effects later to these images later and is the reason im not using css to load the images), that said i'm currently having difficulty loading a image on to the canvas. here is the code:

<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>

不正确加载图片,但我不确定。

I think that i'm not loading the image correctly but i'm not sure.

推荐答案

将onload事件侦听器移动到

move the onload event listener to before you set the src for the image.

    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';

这篇关于使用javaScript将图像加载到画布上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆