Loading an image onto a canvas with javaScript

前端 未结 4 1875
我寻月下人不归
我寻月下人不归 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条回答
  •  Happy的楠姐
    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';
        }
    }
    

提交回复
热议问题