Loading an image onto a canvas with javaScript

前端 未结 4 1870
我寻月下人不归
我寻月下人不归 2020-12-30 02:34

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

相关标签:
4条回答
  • 2020-12-30 02:53

    There are a few things:

    1. drawimage should be drawImage - note the capital i.
    2. Your getElementById is looking for an element with ID of canvas, but it should be test1. canvas is the tag, not the ID.
    3. Replace the canvas variable (e.g. in your canvas.getContext lines) with ctx, since that's the variable you've used to select your canvas element.
    4. Bind your onload handler before you set the src of the image.

    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';
        }
    }
    
    0 讨论(0)
  • 2020-12-30 02:56

    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';
    
    0 讨论(0)
  • 2020-12-30 03:06

    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.

    var loadImage = function (url, ctx) {
      var img = new Image();
      img.src = url
      img.onload = function () { 
        ctx.drawImage(img, 0, 0);
      }
    }
    
    0 讨论(0)
  • 2020-12-30 03:07

    Using newer JavaScript features:

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

    and the loadImage function looks like this:

    function loadImage(url) {
      return new Promise(r => { let i = new Image(); i.onload = (() => r(i)); i.src = url; });
    }
    
    0 讨论(0)
提交回复
热议问题