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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14757659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:48:31  来源:igfitidea点击:

Loading an image onto a canvas with javaScript

javascripthtmlcanvas

提问by dee Five

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:

大家好,我目前正在测试使用 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>

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

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

回答by freejosh

There are a few things:

有几件事:

  1. drawimageshould be drawImage- note the capital i.
  2. Your getElementByIdis looking for an element with ID of canvas, but it should be test1. canvasis the tag, not the ID.
  3. Replace the canvasvariable (e.g. in your canvas.getContextlines) with ctx, since that's the variable you've used to select your canvas element.
  4. Bind your onloadhandler before you set the srcof the image.
  1. drawimage应该drawImage- 注意大写 i。
  2. getElementById正在寻找 ID 为 的元素canvas,但它应该是test1canvas是标签,而不是 ID。
  3. canvas变量(例如在您的canvas.getContext行中)替换为ctx,因为这是您用来选择画布元素的变量。
  4. onload在设置src图像之前绑定您的处理程序。

So your function should end up like this:

所以你的函数应该是这样的:

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

回答by dee Five

Using newer JavaScript features:

使用较新的 JavaScript 功能:

let img = await loadImage("./my/image/path.jpg");
ctx.drawImage(img, 0, 0);

and the loadImagefunction looks like this:

loadImage函数如下所示:

function loadImage(url) {
  return new Promise(r => { let i = new Image(); i.onload = (() => r(i)); i.src = url; });
}

回答by Iwan

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

在为图像设置 src 之前将 onload 事件侦听器移动到。

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

回答by Yohanes AI

Assign your local file resource (url) to image source and draw image using context from canvas you want to load. That's it. See code bellow.

将您的本地文件资源 (url) 分配给图像源并使用您要加载的画布中的上下文绘制图像。就是这样。请参阅下面的代码。

var loadImage = function (url, ctx) {
  var img = new Image();
  img.src = url
  img.onload = function () { 
    ctx.drawImage(img, 0, 0);
  }
}