将canvas转换为base64错误

时间:2016-06-22 03:19:38

标签: javascript

结果转换为空png图像,请帮助我

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 个答案:

答案 0 :(得分:3)

你必须在图像的onload事件中包含所有内容(绘制到画布+从中读取+在其他地方设置)。由于跨域问题,它不会对此代码段(对toDataURL的调用)起作用,但它可以在您的网站上运行。

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

&#13;
&#13;
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();
&#13;
<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'>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

改为使用document.getElementById('bannerImg').setAttribute('src', dataurl);

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();

示例:https://jsfiddle.net/atg5m6ym/6152/