gpt4 book ai didi

javascript - canvas转base64报错

转载 作者:行者123 更新时间:2023-11-30 11:56:00 26 4
gpt4 key购买 nike

结果转换为空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 事件中包含所有内容(绘制到 Canvas + 从 Canvas 读取 + 在其他地方设置)。由于跨域问题,它不适用于此代码段(对 toDataURL 的调用),但它应该适用于您的网站。

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'>

关于javascript - canvas转base64报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37957956/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com