0

I have a JS script that works with an HTML canvas to:

  1. draw a background image onto the canvas element, and

  2. draw lines/other information onto the canvas. (It's for dimensional measurements on furniture).

However, when moving the script from local to a live site, I believe the loading time of the image is throwing off the script.

JSFiddle example

The chunk of the code that deals with image loading:

this.sbCanvasElement = $('#'+CanvasDOMRef);
var can = document.getElementById(CanvasDOMRef);
this.sbCanvas = can.getContext('2d');

this.sbCanvasElement.css("background-image","url('"+this.sbImage+"')");
this.sbCanvasElement.css("background-positon","0px 0px");

This section of the script grabs the Canvas element and sets the background image to the URL previously stored in the object.

The result can either be

  • Successful

    Screenshot of success

  • Failure

    Screenshot of failure

I believe I have to interrupt the script while the image is loaded, but I am not sure of the best approach. Any ideas?

BryanH
  • 5,826
  • 3
  • 34
  • 47
connormw
  • 23
  • 3
  • You can use an image preloader to be sure both your images are loaded before you try to use the images. Here's an [example](http://stackoverflow.com/questions/30578521/how-do-image-preloaders-work). – markE Mar 17 '16 at 17:16

1 Answers1

2

You can use onload event for the image, but you need to change the css() method with drawImage() canvas method.

  var imageObj = new Image();
  var context = this.sbCanvas;
  var coord = { x: 0, y: 0 };
  imageObj.onload = function() {
    context.drawImage(imageObj, coord.x, coord.y);
  };
  imageObj.src = 'your-image-url.jpg';
Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69