oscarvady
oscarvady

Reputation: 450

Inserting Canvas into an img tag

I'd like insert the canvas data into an img tag. That's possible?

<canvas id="myCanvas" width="200px" height="200px" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag.</canvas>

<img id="insertHereTheCanvas" src="" alt="" width="200px" height="200px" style="border:1px solid #d3d3d3;"></img>

If I use canvas.toDataURL("image/png"); I can see a value how this: data:image/png;base64,iVBORw...

But I'd like to fill the img tag content and load the same image than the canvas. Here is my code so far:

$(document).ready( function(){
    var c=$("#myCanvas")[0];
    var ctx = c.getContext("2d");
    var img = new Image(200,200);
    img.src = "http://www.nimbosfera.com/uploads/empresas/empresa-235.jpg?20140920";
    img.onload = function () {
        ctx.drawImage(img,0,0);
        ctx.textAlign="center";
        ctx.font = "12pt Courie bold";
        ctx.fillText("MI TEXTO", 100, 150);
    }


  var dataURL = c.toDataURL("image/png");
  alert(dataURL); // data:image/png;base64,iVBORw...

})

Here the question on fiddle

Thanks in advance

Upvotes: 1

Views: 139

Answers (1)

user1693593
user1693593

Reputation:

  • Make sure image is loaded from same origin (typically domain) or you need to set crossOrigin to anonymous (see fiddle) or you'll get an security error when extracting the image to data-uri (please note: this may or may not be the case for your final page, but from the fiddle this is evident - I copied the image to a host which supports cross-origin use).
  • You can set image source directly with the data-uri toDataURL() returns.
  • Make sure to extract the data-uri AFTER image has loaded properly and been drawn, ie. inside the onload handler, or you'll risk ending up with an empty canvas and string. You probably want to call your next step in the code from here as well.

Modified fiddle

Upvotes: 3

Related Questions