HTML5最重要的一块内容就是canvas画布,可以用js实现很多图片处理的功能。
<canvas id="canvas"></canvas> <img src="img/codebg.png" id="bg">
var w = document.documentElement.clientWidth || document.body.clientWidth; var h = document.documentElement.clientHeight || document.body.clientHeight; h-=70; var bg=document.getElementById("bg"); var imgCode=sessionStorage.getItem("codeImg"); var canvas=""; bg.onload = function(){ canvas=document.getElementById("canvas"); canvas.width = w; canvas.height = h; var ctx=canvas.getContext("2d"); ctx.drawImage(bg, 0, 0, ctx.canvas.width, ctx.canvas.height); var img= new Image(); img.src=imgCode; img.onload=function(){ ctx.drawImage(img, w-h/6.67-28, h-h/6.67-38, h/6.67, h/6.67); downloadFile('tox.png', canvas.toDataURL("image/png")); }; }; function base64Img2Blob(code){ var parts = code.split(';base64,'); var contentType = parts[0].split(':')[1]; var raw = window.atob(parts[1]); var rawLength = raw.length; var uInt8Array = new Uint8Array(rawLength); for (var i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array], {type: contentType}); } function downloadFile(fileName, content){ var aLink = document.createElement('a'); aLink.className="button"; aLink.innerHTML="保存图片"; var blob = base64Img2Blob(content); aLink.download = fileName; aLink.href = URL.createObjectURL(blob); document.body.appendChild(aLink); }
效果如下: