UNPKG

cdt-cli

Version:

A simple CLI for creating your projects

77 lines (65 loc) 2.18 kB
'use strict' let watermark = {} let setWatermark = (str) => { let id = '1.23452384164.123412415' if (document.getElementById(id) !== null) { document.body.removeChild(document.getElementById(id)) } let can = document.createElement('canvas') can.width = 300 can.height = 80 CanvasRenderingContext2D.prototype.wrapText = function (text, x, y, maxWidth, lineHeight) { if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') { return; } var context = this; var canvas = context.canvas; if (typeof maxWidth == 'undefined') { maxWidth = (canvas && canvas.width) || 400; } if (typeof lineHeight == 'undefined') { lineHeight = (canvas && parseInt(window.getComputedStyle(canvas).lineHeight)) || parseInt(window.getComputedStyle(document.body).lineHeight); } // 字符分隔为数组 var arrText = text.split(''); var line = ''; for (var n = 0; n < arrText.length; n++) { var testLine = line + arrText[n]; var metrics = context.measureText(testLine); var testWidth = metrics.width; if (testWidth > maxWidth && n > 0) { context.fillText(line, x, y); line = arrText[n]; y += lineHeight; } else { line = testLine; } } context.fillText(line, x, y); }; let cans = can.getContext('2d') cans.rotate(-5 * Math.PI / 180) cans.font = '20px Vedana' cans.fillStyle = 'rgba(200, 200, 200, 0.30)' cans.textAlign = 'left' cans.textBaseline = 'Middle' cans.wrapText(str, 0, 40,300,40) cans.save() let div = document.createElement('div') div.id = id div.style.pointerEvents = 'none' div.style.top = '70px' div.style.left = '0px' div.style.position = 'fixed' div.style.zIndex = '22' div.style.width = document.documentElement.clientWidth + 'px' div.style.height = document.documentElement.clientHeight + 'px' div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat' document.body.appendChild(div) return id } // 该方法只允许调用一次 watermark.set = (str) => { setWatermark(str) } export default watermark