用canvas做水印以文字中心旋转(Vue指令方式)

import Vue from 'vue'

// 注册全局自定义指令 水印 'v-watermark'
Vue.directive('watermark', (el, binding) => {
    const {
        content,
        rotate = 20,
        fontColor = '#999999',
        fontSize = 16,
        top = 30,
        bottom = 30,
        left = 30,
        right = 30,
        show = false
    } = binding.value || {};
    if (show && content) {

        const canvasDom = document.createElement('canvas');
        el.appendChild(canvasDom);
        canvasDom.style.display = 'none';
        let ctx = canvasDom.getContext('2d');
        ctx.font = `${fontSize}px sans-serif`;
        // 查看内容占用宽
        const contentWidth = ctx.measureText(content).width;
        // canvas要以文字中心旋转
        const { x, y } = getCenter(contentWidth, top, left, fontSize)
        // 设置 canvasDom 的宽高
        canvasDom.width = left + right + contentWidth;
        canvasDom.height = top + bottom + fontSize;
        console.log(top + bottom + fontSize, x, y)
        // 偏移和角度
        ctx.translate(x, y);
        ctx.rotate(Math.PI / 180 * rotate);
        ctx.translate(-x, -y);
        // 避免font被重置
        ctx.font = `${fontSize}px sans-serif`;
        // 颜色
        ctx.fillStyle = fontColor;
        // 文字左顶点为基准点
        ctx.textAlign = 'left';
        ctx.textBaseline = 'top';
        // 画文字
        ctx.fillText(content, left, top);

        el.style.backgroundImage = 'url(' + canvasDom.toDataURL('image/png') + ')';
        el.removeChild(canvasDom);
    } else {
        el.style.backgroundImage = '';
    }
    // 获取中心点
    function getCenter(contentWidth, top, left, fontSize) {

        return {
            x: contentWidth / 2 + left,
            y: fontSize / 2 + top
        }
    }
})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。