Javascript using callback to draw an image to canv

2019-08-08 19:50发布

I think I'm having a similar issue to this question, but I would like a little help understanding how to use a callback function and how to implement it for my particular situation. I'm trying to have an image get drawn to a canvas "on demand", i.e. any time a certain function is called. The image is associated with an object I call a Block. A Block has dimensions, coordinates, and a url.

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

function Block(x, y, width, height, url) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.url = url;
        this.drawBlock = drawBlock;
        function drawBlock() {
              var blockSprite = new Image();
              blockSprite.src = url;
              blockSprite.onload = context.drawImage(blockSprite,x,y,width,height);
        }
  }

You can see a demo here. Oddly enough, it works if I link to an image on the web, but fails if I link to an image on my disk. I believe that this is because the onload event occurs before drawBlock is called, and that I need to use callbacks or promises to fix this, but I'm very new to Javascript so I'd like a little guidance here. Any help or advice would be appreciated.

1条回答
男人必须洒脱
2楼-- · 2019-08-08 20:32

Try it this way:

function Block(x, y, width, height, url) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.url = url;
        this.drawBlock=function drawBlock(){
              var blockSprite = new Image();
              blockSprite.src = url;
              blockSprite.onload = function(){
                  context.drawImage(blockSprite,x,y,width,height);
              }
        }
  }

var block=new Block(0,0,32,32,"house32x32.png");
block.drawBlock();

A callback is simply a function that is executed at a later time--usually after a long-running task has finally been completed.

Loading an image is a good example. Consider this code:

function someCallbackFunction(){
    alert("The image has finally been fully loaded");
}

var image=new Image();

image.onload=someCallbackFunction;

image.src="yourImage.png";

alert("This code is last, but will execute before the onload function");

It will actually execute in this order:

  1. The image object is created.

    var image=new Image();

  2. The image object is told that when it's done fully loading the image it should execute the function called someCallbackFunction.

    image.onload=someCallbackFunction

  3. The image is given a .src URL and begins the long process of downloading the image

    image.src="yourImage.png";

  4. Any code after image.src="yourImage.png" will execute.

  5. ...Sometime later...After the image is fully loaded, the image object will execute someCallbackFunction() and the alert will sound.

查看更多
登录 后发表回答