簡單的前端水印(canvas)

前幾天作項目,客戶要求在頁面中添加水印,在查詢一段資料後,就本身改了些東西,想到了canvas,想到就去作;css

代碼:js地址:https://home.400gb.com/#item-files/action-indexhtml

function textBecomeImg(text,fontsize,fontcolor){
        var canvas = document.createElement('canvas');
        $buHeight = 0;
        if(fontsize <= 32){ $buHeight = 45; }
        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.fillStyle = fontcolor;
        context.font=fontsize+"px Arial";
        context.textAlign = "center";
        context.textBaseline = 'middle'; 
        context.fillText(text,0,fontsize/2);
        var canvasWidth = canvas.width/99;
        canvasWidth = context.measureText(text).width;
        canvas.width = 250;
        canvas.height = 100;
        context.fillStyle = fontcolor;
        context.font=fontsize+"px Arial";
        context.textBaseline = 'middle'; 
        context.fillText(text,0,fontsize/2);
        var dataUrl = canvas.toDataURL('image/png');
        return dataUrl;
  }
  function  contant(cont,left,top) { 
    var text = cont;
    var shuiyinDiv = document.createElement('div');
    var style = shuiyinDiv.style;
    style.position = 'absolute';
    style.left = left;
    style.top = top;
    style.width = '250%';
    style.height = '300%';
    style.opacity = '0.15';
    style.background = "url("+textBecomeImg(text,22,"red")+")";
    style.zIndex = 9999999991;
    style.transform = "rotate(-30deg)";
    style.pointerEvents = "none";
  document.getElementById('contant').appendChild(shuiyinDiv);
   }
//調用的時候:
  contant('測試水印','-60%','-60%');
  //但須要調用屢次的時候,咱們須要把縱座標進行調整就好了
 
  contant('測試水印1','-60%','-55%')

  contant('測試水印2','-60%','-50%')
 

實現的邏輯主要就是經過canvas新建div實現的;上面的代碼中canvas

document.getElementById('contant').appendChild(shuiyinDiv);能夠更改成
document.body.appendChild(shuiyinDiv);
這樣的話內容就會被添加到body當中,由於這樣的話,咱們沒法獲取頁面的實際高度,因此會出險只有當前屏幕有水印的結果;
因此我在頁面中是這樣寫的,用一個div存放水印,div經過定位定到當前頁面,設置寬高百分百,這樣就能達到全部內容下都有水印。
html代碼:
  <div id="contant"></div>

css:app

 html,body{
      width: 100%;
      height: 100%;
      overflow: auto;
    }
    #contant{
      width: 100%;
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      overflow: hidden;
      z-index: -2
    }

須要的拿走,謝謝!!!測試

相關文章
相關標籤/搜索