0

I tried everything to get this work but didn't happen. Want a method to combine two images (that they are overlayed somehow).

I tried it like described here: Merge Image using Javascript

With this Code:

var c=document.createElement("canvas"); c.width = 100; c.height = 100; var ctx=c.getContext("2d"); var imageObj1 = new Image(); imageObj1.src = base64String; var imageObj2 = new Image(); imageObj1.onload = function() { ctx.drawImage(imageObj1, 0, 0, 328, 526); imageObj2.src = "2.png"; imageObj2.onload = function() { ctx.drawImage(imageObj2, 15, 85, 300, 300); var img = c.toDataURL("image/png"); } }; 

But it doesn't work.

I get the first image by Base64 from Local Storage (as described here) like this:

var img = new Image(); img.src = base64String; 

And the base64 String looks like this: data:image/png;base64,iVBORw0KGgoAAAANS....

Does this somehow break this approach with canvas? Any help is appreciated :) took me already hours and can't figure it out....

12
  • What does not work ? Also are you sure about the 100x100 canvas size ? because you are trying to draw Image with 328x526 size. Commented Aug 18, 2015 at 9:40
  • I think imageObj2.src = "2.png"; it may not be a valid src, check dev-tool to see if imageObj2 is successfully loaded. Commented Aug 18, 2015 at 9:41
  • also tried it with bigger size. This is only an example. It does not generate the "img". So if I want to add the img to an img-Tag in HTML you'll see nothing. If I add only the imageObj1 (created by base64 from Local Storage) this image is shown as well the imageObj2 alone is shown. But to combine them and write back in "img" does not work Commented Aug 18, 2015 at 9:43
  • @fuyushimoya it is. as see my answer above and to give the correct path in my App it is: imageObj2.src = "www/img/dummy-pic.png"; Commented Aug 18, 2015 at 9:45
  • Then try to move the onload before setting the src. You use dataUrl, it may be already loaded when the onload handler registering, so it won't trigger. Or you can use if(image.complete) {call the hander yourself} else {image.onload = handler}. Commented Aug 18, 2015 at 9:46

1 Answer 1

0

Fixed it like this:

var c = document.createElement('canvas'); c.width = 82; c.height = 75; var ctx = c.getContext("2d"); var imageObj2 = new Image(); imageObj2.onload = function (){ ctx.drawImage(imageObj2, 0, 0, 82, 75); var imageObj1 = new Image(); imageObj1.onload = function (){ imageObj1.style.objectFit = "cover"; ctx.drawImage(imageObj1, 14, 4, 53, 53); }; imageObj1.src = data.elephant; }; imageObj2.src = "2.png"; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.