web之svg实现水印、btoa、querySelector、createElement、setAttribute、window、calc、position、relative、absolute


1、html

<div class="watermark_box">
	<div class="watermark"></div>
	<img src="https://s.cn.bing.net/th?id=OHR.SwallowtailFlower_ZH-CN5950463168_1920x1080.jpg" />
</div>

2、JavaScript

function waterDocumentSvg({
    
    
	width = '130px',
	height = '50px',
	x = '37px',
	y = "30px",
	opacity = '0.5',
	rotate = -20,
	fontSize = '17px',
	content = '请勿外传',
	zIndex = 9,
	color = "#34363B"
} = {
    
    }) {
    
    
	let svgStr = `<svg xmlns="http://www.w3.org/2000/svg" width="${
      
      width}" height="${
      
      height}">
			<text x="${
      
      x}" y="${
      
      y}" transform = "rotate(${
      
      rotate},0,0)" opacity="${
      
      opacity}" font-size="${
      
      fontSize}" fill="${
      
      color}">${
      
      content}</text>
		</svg>`,
		base64Url = `data:image/svg+xml;base64,${
      
      window.btoa(unescape(encodeURIComponent(svgStr)))}`,
		dom = document.querySelector('.watermark') || document.createElement("div"),
		styleStr = `z-index: ${
      
      zIndex}; background-image: url('${
      
      base64Url}')`;
	
		dom.setAttribute('style', styleStr);
}

waterDocumentSvg({
    
    
	// 水印区域宽度
	width: '97px',
	// 水印区域高度
	height: '70px',
	// 文字左边距
	x: '30px',
	// 文字上边距
	y: "26px",
	// 文字透明度
	opacity: '0.5',
	// 旋转角度
	rotate: 20,
	// 文字大小
	fontSize: '24px',
	// 水印内容
	content: '水 印',
	// 水印元素层级
	zIndex: 9,
	// 文字颜色
	color: "#34363B"
});

3、css

.watermark_box {
    
    
	margin-top: 70px;
	margin-left: 70px;
	width: calc(100vh - 300px);
	height: calc(100vh - 500px);
	position: relative;
}

.watermark_box>img {
    
    
	width: 100%;
	height: 100%;
}

.watermark {
    
    
	position: absolute;
	top: 0;
	left: 0;
	width: calc(100vh - 300px);
	height: calc(100vh - 500px);
	/* 鼠标穿透 */
	pointer-events: none;
}

猜你喜欢

转载自blog.csdn.net/weixin_51157081/article/details/125391822