生成html水印,兼容ie8,ie兼容性问题与解决办法

csharp

浏览数:2,311

2019-1-7

片段 1片段 2</a片段 3片段 4片段 5


watermark.js

// 水印
(function (watermark) {
    window.watermarkdivs = [];
    // 加载水印
    var loadMark = function (settings) {
        var defaultSettings = {
            watermark_txt: "测试水印",
            watermark_x: 20,//水印起始位置x轴坐标
            watermark_y: 20,//水印起始位置Y轴坐标
            watermark_rows: 0,//水印行数
            watermark_cols: 0,//水印列数
            watermark_x_space: 100,//水印x轴间隔
            watermark_y_space: 50,//水印y轴间隔
            watermark_font: '微软雅黑',//水印字体
            watermark_color: 'black',//水印字体颜色
            watermark_fontsize: '18px',//水印字体大小
            watermark_alpha: 0.15,//水印透明度,要求设置在大于等于0.003
            watermark_width: 150,//水印宽度
            watermark_height: 100,//水印长度
            watermark_angle: 15,//水印倾斜度数
        };
        //采用配置项替换默认值,作用类似jquery.extend
        if (arguments.length === 1 && typeof arguments[0] === "object") {
            var src = arguments[0] || {};
            for (key in src) {
                if (src[key] && defaultSettings[key] && src[key] === defaultSettings[key])
                    continue;
                else if (src[key])
                    defaultSettings[key] = src[key];
            }
        }

        if (window.watermarkdivs && window.watermarkdivs.length > 0) {
            document.body.removeChild(document.getElementById("otdivid"));
            window.watermarkdivs = [];
        }

        //获取页面最大宽度
        var page_width = Math.max(document.body.scrollWidth, document.body.clientWidth);
        //获取页面最大长度
        var page_height = Math.max(document.body.scrollHeight, document.body.clientHeight);
        // var page_height = Math.max(document.body.scrollTop,document.body.clientHeight);

        // 创建文档碎片
        var oTemp = document.createDocumentFragment();
        //创建水印外壳div
        var otdiv = document.getElementById("otdivid");

        if (!otdiv) {
            otdiv = document.createElement('div');
            otdiv.id = "otdivid";
            otdiv.style.pointerEvents = "none";
            document.body.appendChild(otdiv);
        }

        //如果将水印列数设置为0,或水印列数设置过大,超过页面最大宽度,则重新计算水印列数和水印x轴间隔
        if (defaultSettings.watermark_cols == 0 || (parseInt(defaultSettings.watermark_x + defaultSettings.watermark_width * defaultSettings.watermark_cols + defaultSettings.watermark_x_space * (defaultSettings.watermark_cols - 1)) > page_width)) {
            defaultSettings.watermark_cols = parseInt((page_width - defaultSettings.watermark_x + defaultSettings.watermark_x_space) / (defaultSettings.watermark_width + defaultSettings.watermark_x_space));
            defaultSettings.watermark_x_space = parseInt((page_width - defaultSettings.watermark_x - defaultSettings.watermark_width * defaultSettings.watermark_cols) / (defaultSettings.watermark_cols - 1));
        }
        //如果将水印行数设置为0,或水印行数设置过大,超过页面最大长度,则重新计算水印行数和水印y轴间隔
        if (defaultSettings.watermark_rows == 0 || (parseInt(defaultSettings.watermark_y + defaultSettings.watermark_height * defaultSettings.watermark_rows + defaultSettings.watermark_y_space * (defaultSettings.watermark_rows - 1)) > page_height)) {
            defaultSettings.watermark_rows = parseInt((defaultSettings.watermark_y_space + page_height - defaultSettings.watermark_y) / (defaultSettings.watermark_height + defaultSettings.watermark_y_space));
            defaultSettings.watermark_y_space = parseInt(((page_height - defaultSettings.watermark_y) - defaultSettings.watermark_height * defaultSettings.watermark_rows) / (defaultSettings.watermark_rows - 1));
        }

        var x;
        var y;
        for (var i = 0; i < defaultSettings.watermark_rows; i++) {
            y = defaultSettings.watermark_y + (defaultSettings.watermark_y_space + defaultSettings.watermark_height) * i;
            for (var j = 0; j < defaultSettings.watermark_cols; j++) {
                x = defaultSettings.watermark_x + (defaultSettings.watermark_width + defaultSettings.watermark_x_space) * j;

                var mask_div = document.createElement('div');
                var oText = document.createTextNode(defaultSettings.watermark_txt);
                mask_div.appendChild(oText);
                // 设置水印相关属性start
                mask_div.id = 'mask_div' + i + j;
                mask_div.onselectstart = "return false";
                //设置水印div倾斜显示
                mask_div.style.filter = "progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand', M11=0.96593, M12=0.25882, M21=-0.25882, M22=0.96593) progid:DXImageTransform.Microsoft.Alpha(opacity=15)";
                //逆时针旋转45度:progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand', M11=0.70710678118655, M12=0.70710678118655, M21=-0.70710678118655, M22=0.70710678118655);
                mask_div.style.webkitTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";

                mask_div.style.MozTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";
                mask_div.style.msTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";
                mask_div.style.OTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";
                mask_div.style.transform = "rotate(-" + defaultSettings.watermark_angle + "deg)";
                mask_div.style.visibility = "";
                mask_div.style.position = "absolute";
                //选不中

                mask_div.style.left = x + 'px';
                mask_div.style.top = y + 'px';
                mask_div.style.overflow = "hidden";
                mask_div.style.zIndex = "9999";
                //mask_div.style.border="solid #eee 1px";
                mask_div.style.opacity = defaultSettings.watermark_alpha;
                mask_div.style.fontSize = defaultSettings.watermark_fontsize;
                mask_div.style.fontFamily = defaultSettings.watermark_font;
                mask_div.style.color = defaultSettings.watermark_color;
                mask_div.style.textAlign = "center";
                mask_div.style.width = defaultSettings.watermark_width + 'px';
                mask_div.style.height = defaultSettings.watermark_height + 'px';
                mask_div.style.display = "block";
                //设置水印相关属性end
                //附加到文档碎片中
                otdiv.appendChild(mask_div);
                otdiv.style.cursor = "default";                window.watermarkdivs.push(otdiv); //控制页面大小变化时水印字体
            };
        };
        //一次性添加到document中
        document.body.appendChild(oTemp);
    };

    watermark.init = function (settings) {
        window.onload = function () {
            loadMark(settings);
        };
        window.onresize = function () {
            loadMark(settings);
        };
    };

    watermark.load = function (settings) {
        loadMark(settings);
    };

})(window.watermark = {});


pointer_events_polyfill.js

/*
 * Pointer Events Polyfill: Adds support for the style attribute
 * "pointer-events: none" to browsers without this feature (namely, IE).
 * (c) 2013, Kent Mewhort, licensed under BSD. See LICENSE.txt for details.
 */

// constructor
function PointerEventsPolyfill(options) {
    // set defaults
    this.options = {
        selector: '*',
        mouseEvents: ['click', 'dblclick', 'mousedown', 'mouseup'],
        usePolyfillIf: function () {
            // if (navigator.appName == 'Microsoft Internet Explorer')
            // {
            /* jshint ignore:start */
            var agent = navigator.userAgent;
            // if (agent.match(/MSIE ([0-9]{1,}[\.0-9]{0,})/) != null) {
            //     var version = parseFloat(RegExp.jQ1);
            //     if (version < 11)
            return true;
            // }
            /* jshint ignore:end */
            // }
            // return false;
        }
    };
    if (options) {
        var obj = this;
        $.each(options, function (k, v) {
            obj.options[k] = v;
        });
    }

    if (this.options.usePolyfillIf())
        this.register_mouse_events();
}/**
 * singleton initializer
 *
 * @param   {object}    options     Polyfill options.
 * @return  {object}    The polyfill object.
 */

PointerEventsPolyfill.initialize = function (options) {
    /* jshint ignore:start */
    if (PointerEventsPolyfill.singleton == null)
        PointerEventsPolyfill.singleton = new PointerEventsPolyfill(options);
    /* jshint ignore:end */
    return PointerEventsPolyfill.singleton;
};/**
 * handle mouse events w/ support for pointer-events: none
 */
PointerEventsPolyfill.prototype.register_mouse_events = function () {
    // register on all elements (and all future elements) matching the selector
    $(document).on(
        this.options.mouseEvents.join(' '),
        this.options.selector,
        function (e) {
            if ($(this).css('pointerEvents') == 'none') {

                // peak at the element below
                var origDisplayAttribute = $(this).css('display');
                $(this).css('display', 'none');

                var underneathElem = document.elementFromPoint(
                    e.clientX,
                    e.clientY);

                if (origDisplayAttribute)
                    $(this)
                        .css('display', origDisplayAttribute);
                else
                    $(this).css('display', '');

                // fire the mouse event on the element below
                e.target = underneathElem;
                $(underneathElem).trigger(e);
                return false;
            }
            return true;
        });
};


使用之前先引用jQuery

$(function () {
            window.setInterval(function () {
                watermark.load({ watermark_txt: "我是谁?" });
            }, 200);
            PointerEventsPolyfill.initialize({});
        });


页面文字特效

跳动文字代码

<MARQUEE behavior=alternate direction=up height=98 scrollAmount=5>

<MARQUEE behavior=altrnate scrollAmount=2 width=460>

<FONT color=red face=楷体_gb2312 size=7>要设置的文字</FONT>

</MARQUEE></MARQUE>

3D文字效果

<style type="text/css">

.3dfont { FILTER: glow(color=ffffff,strength=0) shadow(color=cccccc,direction:135); POSITION: relative; WIDTH: 100% }

</style>

<table border="0" width="100%">

<tr>

<td width="100%" class="3dfont"><font color="#008040">要设置的文字</font>

高斯模糊字体

<span style="position:relative; width:200; height:50; filter:glow(color=#9933cc,strength=4); margin-left:4px">

<p>要设置的文字</span>

文字左右反转

<table style="Filter:FlipH">要设置的文字</table>

文字上下反转

<table style="Filter:FlipV">要设置的文字</table>

Blur风吹效果

<table style="Filter:Blur(add=1,direction=45,strength=5)要设置的文字</table>

add:是否要在已经使用Blur滤镜上的html对象上显示原来的模糊方向,0表示不显示

direction:模糊方向

strength:模糊半径大小,单位像素,默认为5,取整

Glow滤镜(光晕效果)

<table style="Filter:Glow(color=#FF0000,strength=5,direction=2)">要设置的文字</table>

color:光晕颜色,需用代码形式

strength:光晕强度,选择型参数,默认为5

direction:光晕方向,选择型参数

Shadow滤镜(阴影效果)

<table style="Filter:Shadow(color=#ff0000,direction=45)">要设置的文字</table>

color:阴影颜色,需用代码形式

strength:阴影强度,选择型参数,默认为5

direction:阴影方向,选择型参数

DropShadow(投影效果)

<table style="filter:dropshadow(color:#6600FF,offx=1,offy=1)">要设置的文字</table>

color:设置投影颜色

offx:在横坐标上的偏移,单位是像素

offy:在纵坐标上的偏移,单位是像素

positive:设置是否从对象的非透明像素建立阴影

文字围绕鼠标旋转代码

CSS代码

<script><script>
<!-- Begin
if (document.all) {
yourLogo = "我爱你"; //Not less than 2 letters!
logoFont = "Arial";
logoColor = "ff0000";
//Nothing needs altering below!
yourLogo = yourLogo.split('');
L = yourLogo.length;
TrigSplit = 360 / L;
Sz = new Array()
logoWidth = 100;
logoHeight = -30;
ypos = 0;
xpos = 0;
step = 0.09;
currStep = 0;
document.write('<div id="outer" style="position:absolute;top:0px;left:0px"><div style="position:relative">');
for (i = 0; i < L; i++) {
document.write('<div id="ie" style="position:absolute;top:0px;left:0px;'
+'width:10px;height:10px;font-family:'+logoFont+';font-size:12px;'
+'color:'+logoColor+';text-align:center">'+yourLogo[i]+'</div>');
}
document.write('</div></div>');
function Mouse() {
ypos = event.y;
xpos = event.x - 5;
}
document.onmousemove=Mouse;
function animateLogo() {
outer.style.pixelTop = document.body.scrollTop;
for (i = 0; i < L; i++) {
ie[i].style.top = ypos + logoHeight * Math.sin(currStep + i * TrigSplit * Math.PI / 180);
ie[i].style.left = xpos + logoWidth * Math.cos(currStep + i * TrigSplit * Math.PI / 180);
Sz[i] = ie[i].style.pixelTop - ypos;
if (Sz[i] < 5) Sz[i] = 5;
ie[i].style.fontSize = Sz[i] / 1.7;
}
currStep -= step;
setTimeout('animateLogo()', 20);
}
window.onload = animateLogo;
}
// End -->
</script>


实现简单小水印

//下面是svg生成文字的函数。
function getSVGTextBase64(text, svgStyle) {
  var svgNS = 'http://www.w3.org/2000/svg';
  function createTag(tag, objAttr) {
    var oTag = document.createElementNS(svgNS, tag);
    for (var attr in objAttr) {
      oTag.setAttribute(attr, objAttr[attr]);
    }
    return oTag;
  }

  function encode(input) {

    function utf8_encode(string) {
      string = string.replace(/\r\n/g, "\n");
      var utftext = "";

      for (var n = 0; n < string.length; n++) {

        var c = string.charCodeAt(n);

        if (c < 128) {
          utftext += String.fromCharCode(c);
        }
        else if ((c > 127) && (c < 2048)) {
          utftext += String.fromCharCode((c >> 6) | 192);
          utftext += String.fromCharCode((c & 63) | 128);
        }
        else {
          utftext += String.fromCharCode((c >> 12) | 224);
          utftext += String.fromCharCode(((c >> 6) & 63) | 128);
          utftext += String.fromCharCode((c & 63) | 128);
        }

      }

      return utftext;
    }
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;
    var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    input = utf8_encode(input);
    

    while (i < input.length) {

      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
        enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
        enc4 = 64;
      }

      output = output +
        _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
        _keyStr.charAt(enc3) + _keyStr.charAt(enc4);

    }

    return output;
  }

  svgStyle = Object.assign({
    'width': '50px',
    'height': '50px',
    'text-anchor': 'left',
    'font-size': '12px',
    'transform': 'translate(0 50) rotate(-15)',
    'x': '0',
    'y': '1em',
  }, svgStyle);

  var oSvg = createTag('svg', { 'xmlns': svgNS, 'width': svgStyle.width, 'height': svgStyle.height, });
  var oText = createTag('text', svgStyle);
  oText.innerHTML = text;
  oSvg.appendChild(oText);

  var svgStr = new XMLSerializer().serializeToString(oSvg);
  var bgUrl = 'data:image/svg+xml;base64,' + encode(svgStr);
  return bgUrl;
}