方法:图片转成canvas,从而得到图片的base64码
<div class="box">
<div>
<div>
图片:
</div>
<img src="./img/pie.svg" alt="" id="pie" class="imgs">
</div>
<button id="btn">副本生成=></button>
<div>
<div>
图片(副本):
</div>
<div id="wrap">
</div>
</div>
</div>
<br/>
<div>
<div>图片Base64数据:</div>
<textarea id="dataImg" rows="10" cols="100"></textarea>
</div>
<script>
var btn = document.getElementById("btn");
var dataImg = document.getElementById("dataImg")
btn.addEventListener("click", clickHandler);
//核心代码
function getBase64Img(img) {
let cans = document.createElement("canvas");
cans.width = img.width;
cans.height = img.height;
let ctx = cans.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
let dataURL = cans.toDataURL("image/png");
return dataURL;
}
//
function clickHandler() {
console.log("点击!")
var img = document.getElementById("pie");
var wrap = document.getElementById("wrap");
var data = getBase64Img(img);
console.log("base64数据:", data)
dataImg.value=data;
var imgCopy = document.createElement("img");
imgCopy.src = data;
wrap.appendChild(imgCopy);
}
</script>
效果图
demo下载