Becky
Becky

Reputation: 5605

DrawImage on a dynamically created canvas

First off see this Fiddle

I want to create a canvas on the fly and append it to a particular DIV and draw an inline svg onto the canvas. But does not work as expected.

var randn = '1';

    function createme(){
        alert("completed 0");
          var crCavs = $('<canvas />',{ id : 'mycanvs'+randn })

          $('#album').append(crCavs);
        alert("completed 1");

          var svg2 =document.getElementById('sVgsource'+randn).outerHTML,
              vms =document.getElementById('mycanvs'+randn), // target canvas
              ctx2 =vms.getContext('2d');

          //callback
          svgToImage(svg2, function(img2){
            vms.width =$('#sVgsource'+randn).width();
            vms.height =$('#sVgsource'+randn).height();
            alert("completed 3");
            ctx2.drawImage(img2, 30, 40);
              alert("completed 4");
          }

          function svgToImage(svg2, callback) {
            var nurl = "data:image/svg+xml;utf8," + encodeURIComponent(svg2),
                img2 = new Image;
            //invoke callback
              callback(img2);

              img2.src = nurl;
              alert("completed 2");
          }
    }
    createme();

Upvotes: 0

Views: 381

Answers (1)

user1693593
user1693593

Reputation:

You are missing an end-parenthesis for the svgToImage() function:

svgToImage(svg2, function(img2) {
    vms.width = img2.width;
    vms.height = img2.height;
    alert("completed 3");
    ctx2.drawImage(img2, 0, 0);
      alert("completed 4");
}); // <-- here

There are also some other issues:

Just reuse the canvas element:

var canvCrtrWrp = $('<canvas />',{ id : 'mycanvs'+randn })

...
var vms = canvCrtrWrp[0];  // index 0 is the actual canvas element

You could also use the width from the produced image on the canvas:

svgToImage(svg2, function(img2) {
    vms.width = img2.width;
    vms.height = img2.height;
    ...

Remember to use the onload handler for image (it was removed from the original code).If not an image element is passed back without any actual image data (need some time to load, decode etc.):

 function svgToImage(svg2, callback) {
     var nurl = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg2),
         img2 = new Image;

     img2.onload = function() {
        callback(this);
     }
     ...

etc.

Updated fiddle.

Upvotes: 1

Related Questions