2

Result convert is null png image, pls help me

var img = new Image();
img.src = 'http://advs.jp/cp/barcode/code128.cgi?nt=1&height=80&c=Z103B5-190-311378&.png';
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d"); 
    ctx.drawImage(img, 0, 0, img.width, img.height);
var dataurl = canvas.toDataURL().replace("data:image/jpeg;base64,", "");
    localStorage.setItem("img", dataurl);
 $('#bannerImg').attr('src', dataurl);
  <img id="bannerImg" src="" alt="Banner Image" width="100%" height="200px" alt="Embbed Image"/>
<canvas id="myCanvas"></canvas>

2 Answers2

4

You have to include everything (drawing to canvas + reading from it + setting this elsewhere) in the onload event of the image. It doesn't work on this snippet (the call to toDataURL) due to a cross-domain issue, but it shall work on your website.

An explanation of why it doesn't work here the call to toDataURL

var imgCanvas = function() {     
    var img = new Image();
    //Wait for image to load before doing something with content
    img.onload = function() {
        var canvas = document.getElementById("myCanvas");  
        //Set canvas size to fit the image
        canvas.style.height = img.height + 'px';
        canvas.style.width = img.width + 'px';
      
        //Draw the image in canvas
        var ctx = canvas.getContext("2d");    
        ctx.drawImage(img, 0, 0); 
      
        //Get a dataurl representation of the image where the image itself is in BASE64
        var dataurl = canvas.toDataURL();
      
        //Store it in localStorage
        localStorage.setItem("img", dataurl);  
      
        //Show image from localStorage
        //Need jQuery to use this line instead of next one : $('#bannerImg').attr('src', localStorage.getItem("img")); 
        document.getElementById('bannerImg').setAttribute('src', localStorage.getItem("img"));
    };
    img.src = 'http://advs.jp/cp/barcode/code128.cgi?nt=1&height=80&c=Z103B5-190-311378&.png';
};

imgCanvas();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Canvas:<br>
<canvas id='myCanvas'></canvas>

<br><br>

Image from dataurl:<br>
<img id='bannerImg'>
Community
  • 1
  • 1
Master DJon
  • 1,899
  • 2
  • 19
  • 30
0

Use document.getElementById('bannerImg').setAttribute('src', dataurl); instead.

var showImage = function() {     
    var img = new Image;
    img.onload = function() {
        var canvas = document.getElementById("myCanvas");  
        var ctx = canvas.getContext("2d");    
        ctx.drawImage(img, 0, 0);  
        var dataurl = canvas.toDataURL();
        localStorage.setItem("img", dataurl);  
        document.getElementById('bannerImg').setAttribute('src', dataurl); 
    };
    img.src = 'http://advs.jp/cp/barcode/code128.cgi?nt=1&height=80&c=Z103B5-190-311378&.png';
};

showImage();

Example: https://jsfiddle.net/atg5m6ym/6152/

gotnull
  • 26,454
  • 22
  • 137
  • 203