实现核心的属性是
background-clip 用于对背景裁剪
属性值:
值 | 说明 |
border-box | 默认值。背景绘制在边框方框内(剪切成边框方框) |
padding-box | 背景绘制在衬距方框内(剪切成衬距方框) |
content-box | 背景绘制在内容方框内(剪切成内容方框) |
text | 给文本填充图片背景 |
text-fill-color 用于和背景颜色叠加
- <!DOCTYPE html>
- <html>
- <head>
- <title>背景剪裁属性</title>
- <meta http-equiv=“Content-Type” content=“text/html; charset=utf-8” />
- <style type=“text/css”>
- html,
- body {
- width: 100%;
- height: 100%;
- margin: 0;
- overflow: hidden;
- }
- img {
- float: left;
- }
- p {
- margin: 0;
- font-weight: 600;
- width: 100%;
- overflow: hidden;
- background-repeat: no-repeat;
- background-position: center;
- background-size: contain;
- -webkit-background-clip: text;
- -webkit-text-fill-color: transparent;
- }
- </style>
- </head>
- <body>
- <img src=“css.gif”>
- <p id=“p”>
- 飘动旗帜
- </p>
- <script>
- const p = document.querySelector(‘#p’);
- // 字体大小
- const fontSize = 12
- // 背景图片
- const imgUrl = ‘css.gif’
- p.style.cssText = `font-size:${fontSize}px;line-height:${fontSize}px;`
- const text = p.innerHTML.replace(/(\s+)/g, ”)
- const texttextLength = text.length
- const img = new Image()
- img.src = imgUrl
- img.complete ? onImgLoaded() : (img.onload = onImgLoaded)
- function onImgLoaded() {
- const imgimgRatio = img.width / img.height
- let imgWidth = window.innerWidth
- let imgHeight = imgWidth / imgRatio
- if (imgHeight > window.innerHeight) {
- imgHeight = 200
- imgWidth = imgHeight * imgRatio
- }
- const needTextLength = (imgWidth / fontSize) * (imgHeight / fontSize)
- if (needTextLength > textLength) {
- p.innerHTML = new Array(Math.floor(needTextLength / textLength) + 1).fill(text).join(”)
- }
- p.style.cssText += `width:${imgWidth}px;height:${imgHeight}px;background-image:url(${imgUrl});`
- }
- </script>
- </body>
- </html>
本文链接地址: css字符图像生成