用JS给H5页面增加水印
用JS给H5页面增加水印(watermark),代码示例如下:
import store from "../store"; export function waterMark() { (function waterMarkFulfill() { function textBecomeImg(text, fontsize, fontcolor) { var canvas = document.createElement("canvas"); let 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; var context = canvas.getContext("2d"); context.clearRect(0, 0, canvas.width * 2, canvas.height); context.textAlign = "center"; canvas.width = 160; canvas.height = 130; context.fillStyle = fontcolor; context.font = fontsize + "px Arial"; context.textBaseline = "middle"; var lineHeight = 22; var lines = text.split("\n"); context.fillText(lines[0], 40, fontsize / 2); context.fillText(lines[1], 28, fontsize / 2 + lineHeight); var dataUrl = canvas.toDataURL("image/png"); return dataUrl; } var date = new Date(); var time = date.getFullYear() + "-" + (date.getMonth() + 1).toString().padStart(2, "0") + "-" + date.getDate().toString().padStart(2, "0"); var text = store.getters.realName + "\n" + time; let hasWatermark = document.querySelector(".watermark"); if (!hasWatermark) { var shuiyinDiv = document.createElement("div"); shuiyinDiv.classList.add("watermark"); var style = shuiyinDiv.style; style.position = "fixed"; style.left = "-30%"; style.top = "-60%"; style.width = "200%"; style.height = "200%"; style.opacity = "0.1"; style.background = "url(" + textBecomeImg(text, 16, "gray") + ")"; style.zIndex = 9999999991; style.transform = "rotate(-30deg)"; style.pointerEvents = "none"; document.body.appendChild(shuiyinDiv); } })(); }
效果如下: