// merge the default value function mergeOptions(options) { return Object.assign({ el: 'body', // 需要添加水印的容器 top: '0px', // 水印在容器中的top起始值 left: '0px', // 水印在容器中的left起始值 text: 'water mask', // 显示的水印文本 // 是否允许通过js或开发者工具等途径修改水印DOM节点(水印的id,attribute属性,节点的删除) // true为允许,默认不允许 inputAllowDele: false, // 是否在组件销毁时去除水印节点(前提是允许用户修改DOM,否则去除后会再次自动生成) // true会,默认不会 inputDestroy: false, width: '400', height: '230', alpha: 0.08 // 水印文本透明度 }, options) } var WaterMask = function (options) { this.options = mergeOptions(options) this.maskDiv = {} // 当前显示的水印div节点DOM对象 this.init() } WaterMask.prototype.init = function () { var canvas = document.createElement('canvas') var opt = this.options var width = opt.width var height = opt.height canvas.id = 'canvas' canvas.width = width // 单个水印的宽高 canvas.height = height this.maskDiv = document.createElement('div') var ctx = canvas.getContext('2d') ctx.font = 'normal 18px Microsoft Yahei' // 设置样式 ctx.fillStyle = 'rgba(112, 113, 114,' + opt.alpha + ')}' // 水印字体颜色 ctx.rotate(-Math.PI / 8) // 水印偏转角度 ctx.textAlign = 'left' ctx.textBaseline = 'bottom' ctx.globalAlpha = opt.alpha // text alpha ctx.translate(0, height * 0.5) // margin: 10 ctx.fillText(opt.text, 30, 10) var src = canvas.toDataURL('image/png') this.maskDiv.style.position = 'absolute' this.maskDiv.style.zIndex = '10000000000000099' this.maskDiv.style.top = opt.top this.maskDiv.style.left = opt.left this.maskDiv.style.height = '100%' this.maskDiv.style.width = '100%' this.maskDiv.style.pointerEvents = 'none' this.maskDiv.style.backgroundImage = 'URL(' + src + ')' this.maskDiv.id = '_waterMark' // 水印节点插到body下 // 将水印节点插入到特定组件里 document.querySelector(opt.el).appendChild(this.maskDiv) if (!this.options.inputAllowDele) { // 设置水印节点修改的DOM事件 this.monitor() } } WaterMask.prototype.monitor = function () { var el = document.querySelector(this.options.el) var options = { // childList: true, attributes: true, characterData: true, subtree: true, attributeOldValue: true, characterDataOldValue: true } var observer = new MutationObserver(this.callback.bind(this)) observer.observe(el, options) // 监听节点 } // DOM改变执行callback WaterMask.prototype.callback = function (mutations, observer) { // 当attribute属性被修改 if (mutations[0].target.id === '_waterMark') { this.removeMaskDiv() } // 当id被改变时 if (mutations[0].attributeName === 'id') { this.removeMaskDiv() this.createMaskDiv() } // 当节点被删除 if (mutations[0].removedNodes[0] && mutations[0].removedNodes[0].id === '_waterMark') { this.createMaskDiv() } } // 手动销毁水印DOM WaterMask.prototype.removeMaskDiv = function () { document.querySelector(this.options.el).removeChild(this.maskDiv) } // 手动生成水印 WaterMask.prototype.createMaskDiv = function () { this.init() } window.Watermask = WaterMask