将 JS 代码放入图片文件
var code = 'alert("hello image.");'; var w=6,h=8; // 宽和高的计算方法 w * h * 32 / 8 = code.length // 按3个字符的长度分段 var codeArray = code.match(/.{3}/g); if(codeArray.length * 3 < code.length){ codeArray.push( code.substring( codeArray.length * 3 - 1) ); } for(var i = 0, cl = codeArray.length; i < cl; c++){ codeArray[i] = codeArray[i]+String.fromCharCode(255); } code = codeArray.join(''); // 将代码转为ASCII var buffer = []; for(var i = 0, l = code.length; i < l; i++){ buffer.push(code.charCodeAt(i)); } buffer = new Uint8ClampedArray(buffer); // 将代码转换为图片数据 var imageData= new ImageData(w, h); imageData.data.set(buffer); var canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; var context = canvas.getContext("2d"); context.putImageData(imageData,0,0); base64img = canvas.toDataURL('image/png'); // 在页面中插入图片 var img=document.createElement("img"); img.src=base64img; console.log(base64img); document.body.appendChild(img);