繁体   English   中英

将canvas转换为base64错误

[英]Convert canvas to base64 error

结果转换为null 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> 

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

解释为什么它在这里无法调用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'> 

使用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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM