Vue如何给页面加水印(超简单)

给页面加上水印

  • 用canvas画一张背景图
export default {
    //tool.js
    addWaterMark() {
        const strArr = `${localStorage.getItem(
                "loginUserName"
            )}${localStorage
                .getItem("logunUserPhone")
                .slice(7, 11)}[${new Date()}]`;
        let ctx = document.createElement("canvas");
        ctx.width = 250;
        ctx.height = 100;
        ctx.style.display = "none";
        let cans = ctx.getContext("2d");
        cans.rotate((-20 * Math.PI) / 180);
        cans.font = "12px Microsoft YaHei";
        cans.fillStyle = "rgba(17, 17, 17, 0.20)";
        cans.textAlign = "left";
        cans.textBaseline = "Middle";
        cans.fillText(strArr, 0, 100);
        cans.save();
        return ctx.toDataURL();
    }
}
  • 需要添加的页面引入
<template>
    <div class="content" :style="{backgroundImage:`url(${orgBackground})`}">123</div>
</template>

<script>
import tool from "../plus/tool";
export default {
    data() {
        return {
            orgBackground: "",
        };
    },
    name: "test",
    mounted() {
        localStorage.setItem("loginUserName", "ruan");
        localStorage.setItem("logunUserPhone", "123456");
        //实际只需要一行代码
        this.orgBackground = tool.addWaterMark();
        //监听dom属性改变重新生成水印(如果页面有变化需要去监听dom)
        // const org = document.querySelector(".content");
        // const options = {
        //     attributes: true,
        //     childList: true,
        //     subtree: true,
        // };
        // const observer = new MutationObserver((mutationList) => {
        // this.orgBackground = tool.addWaterMark();
        // });
        // observer.observe(org, options);
    },
};
</script>

<style lang='less' scoped>
.content {
    position: relative;
    width: 100vw;
    height: 100vh;
}
</style>
</script>

在这里插入图片描述

你可能感兴趣的:(vue,css,vue,css,canvas)