JavaScript - js生成 txt 文件 和 canvas 转 png图片

一、JavaScript - js生成 txt 文件


/**
 * 方法定义
 */
function download(filename, text) {
  var element = document.createElement('a');
  element.style.display = 'none';

  var content = encodeURIComponent(text);
  element.setAttribute('href', `data:text/plain;charset=utf-8,${content}`);
  element.setAttribute('download', filename);
 
  document.body.appendChild(element);
  element.click();
 
  document.body.removeChild(element);
}

// 方法调用
download("hello.txt", "Type txt file content here.");

二、JavaScript - canvas 转 png图片

document.querySelectorAll("#contentcontainer canvas")
    .forEach((canvas, idx) => {
 
    function dataURLtoBlob(dataurl) {
    	var arr = dataurl.split(','), 
            mime = arr[0].match(/:(.*?);/)[1],
      	    bstr = atob(arr[1]), 
            n = bstr.length, 
            u8arr = new Uint8Array(n);
    	while(n--){
     		 u8arr[n] = bstr.charCodeAt(n);
    	}
    	return new Blob([u8arr], {type:mime});
  	}

    var link = document.createElement("a");
    var imgData =canvas.toDataURL(
        {format: 'png', quality:1, width:20000, height:4000});
        
    var strDataURI = imgData.substr(22, imgData.length);
    var blob = dataURLtoBlob(imgData);
    var objurl = URL.createObjectURL(blob);
    link.style.display = 'none';
    link.download = `grid-${idx}.png`;
    link.href = objurl;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

});
posted @ 2023-11-14 15:52  炎黄子孙,龙的传人  阅读(242)  评论(0编辑  收藏  举报