Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>使用 Canvas 保存数据的一种思路</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
    <!--[if lt IE 9]>
      <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
    <![endif]-->
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-xs-12">
                <h1 class="example-title">
                    导出测试
                    <div class="pull-right">
                        <button type="button" class="btn btn-default" onclick="_export()">导出</button>
                    </div>
                </h1>
                <textarea class="form-control" rows="25" id="textExported">
{
	"args": {},
	"data": "",
	"files": {},
	"form": {
		"job": "软件开发工程师",
		"location": "中华人民共和国",
		"name": "胡昂",
		"email": "ninedoors at 126 dot com",
		"website": "http://www.markjour.com/"
	},
	"headers": {
		"Accept": "*/*",
		"Connection": "close",
		"Content-Length": "68",
		"Content-Type": "application/x-www-form-urlencoded",
		"Host": "httpbin.org",
		"User-Agent": "curl/7.58.0"
	},
	"json": null,
	"origin": "27.19.139.183",
	"url": "http://httpbin.org/post"
}
</textarea>
                <div id="divExported">
                    <img id="imgExported" class="img-rounded center-block">
                </div>
            </div>
            <div class="col-md-6 col-xs-12">
                <h1 class="example-title">
                    导入测试
                    <div class="pull-right">
                        <input type="file" name="file" class="btn btn-default" id="uploadFile" onchange="_import()"
                            accept="image/png">
                    </div>
                </h1>
                <pre id="preImported"></pre>
                <div id="divUploaded">
                    <img id="imgUploaded" class="img-rounded center-block">
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
</body>

</html>
              
            
!

CSS

              
                .row {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  flex-wrap: wrap;
}
.row > [class*="col-"] {
  display: flex;
  flex-direction: column;
}
.example-title {
  line-height: 80px;
}
#textExported {
  margin-bottom: 10px;
}
#textExported,
#preImported {
  height: 400px;
}
#divExported,
#divUploaded {
  background-color: #eee;
  padding: 10px;
  margin: 0px;
}

              
            
!

JS

              
                // 以下逻辑全部用纯原生代码实现

function createElementFromHTML(html) {
  var emptyElement = document.createElement("empty");
  emptyElement.innerHTML = html.trim();
  return emptyElement.firstChild;
}

var exportedImage = null;
var importedData = null;

function exportData(data) {
  // JSON 序列化
  var strData = JSON.stringify(data);
  // TextEncoder 编码成数字
  var uint8array = new TextEncoder("utf-8").encode(strData);
  // 计算需要多大方阵存储全部数据
  var dataSize = Math.ceil(Math.sqrt(uint8array.length / 3));

  // 用 255 填充 RGBA 中的 alpha 通道,设置完全不透明
  // 否则 alpha = 0,即透明图片)会遇到 RGB 损坏的问题
  // https://stackoverflow.com/questions/22384423/canvas-corrupts-rgb-when-alpha-0
  var paddedData = new Uint8ClampedArray(dataSize * dataSize * 4);
  var idx = 0;
  // 每三个数字后加一个 255
  for (var i = 0; i < uint8array.length; i += 3) {
    var subArray = uint8array.subarray(i, i + 3);
    paddedData.set(subArray, idx);
    paddedData.set([255], idx + 3);
    idx += 4;
  }

  // 生成图像数据
  var imageData = new ImageData(paddedData, dataSize, dataSize);

  // 创建一个屏外(off screen)画布
  var imgSize = 256;
  var canvas = document.createElement("canvas");
  canvas.width = canvas.height = imgSize;
  // 获取画布上下文
  var ctx = canvas.getContext("2d");
  // 画布设置:256 * 256 的黑布
  ctx.fillStyle = "#AA0000"; // 颜色没关系
  ctx.fillRect(0, 0, imgSize, imgSize);
  // 用一个像素的 R 值记录数据规模
  ctx.fillStyle = "rgb(" + dataSize + ", 0, 0)";
  ctx.fillRect(0, 0, 1, 1);
  // 画布填充内容
  ctx.putImageData(imageData, 0, 1);

  var body = document.getElementsByTagName("body")[0];

  exportedImage = canvas.toDataURL();
  var downloadedLink = createElementFromHTML(
    '<a id="hiddenLink" href="' +
      exportedImage +
      '" style="display:;" download="image.png">Download</a>'
  );
  body.appendChild(downloadedLink);

  // MDN 中 Element 没有这个方法,可能不通用
  // downloadedLink.click();

  var e = document.createEvent("MouseEvents");
  e.initEvent("click", true, true);
  // downloadedLink.dispatchEvent(e); // 无效
  var downloadedLink = document.getElementById("hiddenLink");
  downloadedLink.dispatchEvent(e);

  body.removeChild(downloadedLink);
}

// exportData 的反向操作
function importData(imgSrc, callback) {
  var img = new Image();
  img.onload = function() {
    // 先把图片填充到画布上
    var imgSize = img.width;
    var canvas = document.createElement("canvas");
    canvas.width = canvas.height = imgSize;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    // 获取数据规模
    var headerData = ctx.getImageData(0, 0, 1, 1);
    var dataSize = headerData.data[0];

    // 获取数据
    var imageData = ctx.getImageData(0, 1, dataSize, dataSize);
    var paddedData = imageData.data;

    // 抛弃每一个像素数据中的第四位(RGBA 中的 alpha 通道)
    var uint8array = new Uint8Array(paddedData.length / 4 * 3);
    var idx = 0;
    for (var i = 0; i < paddedData.length - 1; i += 4) {
      var subArray = paddedData.subarray(i, i + 3);
      uint8array.set(subArray, idx);
      idx += 3;
    }

    // 将最后为 0 的填充数据去掉
    var includeBytes = uint8array.length;
    for (var i = uint8array.length - 1; i > 0; i--) {
      if (uint8array[i] === 0) {
        includeBytes--;
      } else {
        break;
      }
    }
    var data = uint8array.subarray(0, includeBytes);
    var strData = new TextDecoder("utf-8").decode(data);

    try {
      importedData = JSON.parse(strData);
      if (callback) {
        callback();
      }
    } catch (error) {
      if (callback) {
        callback(error);
      }
    }
  };

  // 可以设置 src 属性为普通 URL 或 Data URL
  img.src = imgSrc;
}

function _export() {
  var strData = document.getElementById("textExported").value;
  console.log("export: strData: " + strData);
  var data = JSON.parse(strData);
  console.log("export: data: " + data);
  exportData(data);
  document.getElementById("imgExported").src = exportedImage;
}

function _import() {
  var iptFile = document.getElementById("uploadFile");
  console.debug(JSON.stringify(iptFile.value));
  console.debug(iptFile.files);

  if (iptFile.value === "" || iptFile.files.length === 0) {
    alert("请选择上传文件!");
    return;
  }

  document.getElementById("preImported").innerText = "";

  var file = iptFile.files[0];
  console.debug(file.size); // 文件字节数

  var imageLink = window.URL.createObjectURL(file);
  importData(imageLink, function(error) {
    if (error) {
      console.error(error);
      alert("图片错误或受损,无法解析!");
    } else {
      var imgUploaded = document.getElementById("imgUploaded");
      imgUploaded.src = imageLink;
    }
    var strData = JSON.stringify(importedData, null, "\t");
    document.getElementById("preImported").innerText = strData;
  });
}

              
            
!
999px

Console