0

I'm trying to use canvas to draw a section of a dom elements background image to the canvas tag. Here is what I have right now.

var draw = function( data ){
    var canvasStr = '<canvas id="highlight" width='300' height='200'></canvas>' 
    var canvasEl = $(canvasStr).appendTo( wrapper );
    var context = canvasEl.get(0).getContext('2d');
    var imgSource = wrapper.find('.invoice').get(0);
    context.drawImage(imgSource, 0, 0, 300, 200);
}

It looks like its not able to read the imageSource from jquery directly. How would I go about this to make it work.

Chapsterj
  • 6,483
  • 20
  • 70
  • 124

1 Answers1

0

try

context.drawImage(imgSource[0], 0, 0, 300, 200);

Your passing the jquery object to drawImage and not the image object. Also be sure the image is loaded before you draw it to the canvas.

EDIT:

Sorry, didn't catch that the image was a background-image. In that case you will need to create a new image from the source of the background image. something like this...

var img = new Image();
img.src = $(wrapper.find('.invoice').get(0)).css('background-image').replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
img.onload = function() {
    context.drawImage(img, 0, 0, 300, 200);
};

Do you see what I mean by make sure the image is loaded? The image takes time to load over the network so it wont be available as soon as you set the source. You have to set up an onload handler to be sure that image is available to be drawn.

hackattack
  • 1,087
  • 6
  • 9
  • Thanks hackattack for the help. What do you mean make sure its loaded?. Its a style background-image on a div.
    this is added when the page loads. The drawImage is called on a click ever well after the page is loaded. Also its not a jquery object its a dom object thats why I use get(0) to turn it from a jquery object to a dom element. var imgSource = wrapper.find('.invoice').get(0);
    – Chapsterj Aug 06 '12 at 21:09
  • So you have to create a dynamic object to hold the image and load it all agin. There is no way to get to the image that is already there? Thanks again for the help – Chapsterj Aug 06 '12 at 21:22
  • Actuually that probably wont even work. You can not access a css background image, so you have to create a new image from the background-image css property. This means you will have to parse the url out of the properity, I doubt css('background-image') returns the url, it probably return url('http://'), you will need to parse the url out of that – hackattack Aug 06 '12 at 21:22
  • What do you mean parse the url? – Chapsterj Aug 06 '12 at 21:27
  • you can read about what im talking about here http://stackoverflow.com/questions/6397529/get-url-from-background-image-property I update the code to reflect this – hackattack Aug 06 '12 at 21:33
  • I just tried what you suggested and it draws an empty canvas element. The src url is showing up a s a local file path. file:///Users/myUsernae/project/images/myImage.jpg – Chapsterj Aug 06 '12 at 21:41