canvas实现水印
最近遇到一个需求,给所有页面加水印(登录人),不影响其他点击等功能的使用,目的是防止信息外漏,当时就在想:这年头,PS就不说人人都能使用,谁手机还没个涂鸦功能,防不了,但是就是这么个需求,那就实现吧!
具体实现思路:在页面底部加一个大的div,给这个div添加背景图,背景图?从哪来?canvas实现吧!
function textBecomeImg(text,fontsize,fontcolor,target){ var canvas = document.createElement('canvas'); $buHeight = 0; if(fontsize <= 32){ $buHeight = 99; } else if(fontsize > 32 && fontsize <= 60 ){ $buHeight = 2;} else if(fontsize > 60 && fontsize <= 80 ){ $buHeight = 4;} else if(fontsize > 80 && fontsize <= 100 ){ $buHeight = 6;} else if(fontsize > 100 ){ $buHeight = 10;} canvas.height=fontsize + $buHeight ; canvas.padding=30; canvas.width = 450; var context = canvas.getContext('2d'); context.clearRect(0, 0, canvas.width*2, canvas.height); context.fillStyle = fontcolor; context.font=fontsize+"px Arial"; context.textAlign = "center"; context.textBaseline = 'middle'; context.fillText(text,0,fontsize/2); var canvasWidth = canvas.width/99; canvasWidth = context.measureText(text).width; var dataUrl = canvas.toDataURL('image/png'); var shuiyinDiv = document.createElement('div'); var style = shuiyinDiv.style; style.position = 'absolute'; style.left = 0; style.top = '-10%'; style.width = '120%'; style.height = '100%'; style.opacity = '0.1'; style.background = "url("+dataUrl+")"; style.zIndex = 9999999991; style.transform = "rotate(-30deg)"; style.pointerEvents = "none"; target.appendChild(shuiyinDiv); }