search
HomeWeb Front-endH5 TutorialFront-end technology realizes text texture overlay

This time I will bring you front-end technology to implement text and text texture overlay. What are the precautions for front-end technology to implement text and text texture overlay. Here are actual cases, let’s take a look.

The overlay mentioned here is overlay in the blending mode. In other words, the effect to be achieved in this article is to overlay the color and texture of the text itself instead of directly filling the texture.

CSS, SVG and canvas can all achieve similar effects. Let’s look at them one by one.

1. CSS/CSS3 implements text texture overlay

The HTML and CSS codes are as follows:

<h2>
    <span></span>
    CSS纹理叠加
</h2>
.pattern-overlay {
    font-size: 60px;
    font-family: 'microsoft yahei';
    background-image: url(./pattern01.jpg); 
    -webkit-text-fill-color: transparent;
    -webkit-background-clip: text;
}
.pattern-overlay > span {
    position: absolute;
    background-image: linear-gradient(to bottom, #f00, #f00);
    mix-blend-mode: overlay;
    -webkit-text-fill-color: transparent;
    -webkit-background-clip: text;
}
.pattern-overlay > span::before {
    content: attr(data-text);    
}

You can achieve something similar The effect of the picture below (red gradient and gray stone texture overlay effect):

Front-end technology realizes text texture overlay

You can click here: CSS to achieve text texture overlay effect demo

In the demo page, we can adjust the starting and ending colors of the gradient image, or change our texture image, all of which will have real-time rendering effects:

Front-end technology realizes text texture overlay

Implementation Principle

Under the webkit browser, the text can be displayed in the background through the following CSS combination:

.fill-bg {
    -webkit-text-fill-color: transparent;
    -webkit-background-clip: text;
}

can be used to achieve text gradient, or Effects similar to the text streamer on the homepage of this website.

Front-end technology realizes text texture overlay

So, we use two layers of labels, clearly fill the gradient background and texture background, and then use the CSS3 blending mode mix-blend-mode:overly to overlay the two layers of labels. , the effect is achieved!

Compatibility

Webkit kernel browser, Chrome, Safari, etc. are all supported.

Explanation on why background-blend-mode is not used

Theoretically, it is the simplest to use background-blend-mode to mix the most background images, because only one layer of performance is needed, theoretically The support code is as follows:

<h2 id="CSS纹理叠加">CSS纹理叠加</h2>
.pattern-overlay {
    font-size: 60px;
    font-family: 'microsoft yahei';
    background-image: linear-gradient(to bottom, #f00, #f00), url(./pattern01.jpg);
    background-blend-mode: overlay;
    -webkit-text-fill-color: transparent;
    -webkit-background-clip: text;
}

There is no problem with background gradient and texture overlay itself. The effect is as follows:

But when applying background- When clip:text is declared, the blending mode is ignored, so the final text has no overlay effect. Therefore, the method of superimposing two independent layers of labels using mix-blend-mode is adopted.

//zxx: CSS3 has natural support for mixed modes. You can refer to this article: "Introduction to CSS3 Mixed Mode mix-blend-mode/background-blend-mode", where mix-blend-mode is the blending between elements, background-blend-mode is the blending between background images.

2. Use SVG to achieve a more compatible text texture overlay effect

The CSS3 method is the easiest to understand and the fastest to get started, but Firefox andIE browser does not support it, so it can only be used on the mobile terminal. If we want to be compatible with PC browsers, we can try to use SVG to achieve it. The code is as follows:

<svg>
  <defs>
    <filter>
     <feimage></feimage>            
     <feblend></feblend>
    </filter>
    <lineargradient>
        <stop></stop>
        <stop></stop>
    </lineargradient>
    <pattern>
        <rect></rect>
    </pattern>
  </defs>
  <text>
    SVG纹理叠加
  </text>
</svg>

Red and green gradient overlay Stone texture, the final effect is as follows:

You can click here: SVG text texture overlay effect demo

Implementation principle

There is a filter element related to blending mode in SVG named , so we can define a and let the graphics refer to the (in="SourceGraphic") and this picture (in2="patternSource") are overlay mixed (mode="overlay").

SVG中文本除了可以填充颜色外,还可以填充纹理,元素是,所以,我们需要一个渐变和纹理素材混合的元素,很简单,一个和SVG尺寸一样的矩形元素,使用渐变填充,应用叠加滤镜,作为纹理。

于是,效果达成!

兼容性

Chrome, Safari, Firefox浏览器都支持。

如果在IE浏览器下访问我们的demo页面,会看到纹理并没有叠加,那是因为,IE浏览器下的只支持规范中提到的几种混合模式,包括:normal,multiply,screen,darken,lighten。并没有叠加overlay。

因此,如果你希望SVG纹理叠加效果IE9+全兼容,可以试试使用正片叠加混合模式-multiply,对于大部分用户而言,是看不出什么差异的。

三、使用canvas实现纹理叠加效果

canvas并没有现成的混合模式api,因此,如果要想实现叠加效果,需要通过算法重新计算方法。关于混合模式的各种算法,实际上都是公开的,搜一搜就能找到。

在本文中,canvas的混合模式效果使用了一个开源的JS方法,项目地址是:https://github.com/Phrogz/context-blender

JS未压缩状态也就9K不到,各种曾经的混合模式都支持。

于是,要使用canvas实现纹理叠加效果那就容易多了。

下面是实现的效果截图:

您可以狠狠地点击这里:canvas实现文本的纹理叠加效果demo

同样的,我们可以修改渐变颜色,修改纹理图片看到其他渲染效果,例如,我们选择本地一张纸张图片作为纹理:

实现原理

绘制JS代码如下:

// 先引入context_blender.js,然后……
// canvas绘制脚本
var canvas = document.querySelector('canvas');
var context = canvas.getContext('2d');
var width = canvas.width, height = canvas.height;
context.textBaseline = 'middle';
context.font = 'bold 60px "Microsoft Yahei"';
// 绘制方法
var draw = function () {    
    context.clearRect(0, 0, width, height);
    // 渐变和纹理
    var gradient, pattern;
    // 创建材质canvas
    var canvasPattern = document.createElement('canvas');
    var contextUnder = canvasPattern.getContext('2d');
    canvasPattern.width = width;
    canvasPattern.height = height;
    // 创建渐变canvas
    var canvasGradient = document.createElement('canvas');
    var contextOver = canvasGradient.getContext('2d');
    canvasGradient.width = width;
    canvasGradient.height = height;
    // 绘制渐变对象
    gradient = contextOver.createLinearGradient(0, 0, 0, height);
    gradient.addColorStop(0, red);
    gradient.addColorStop(1, red);
    // 纹理对象,img指纹理图片对象
    pattern = contextUnder.createPattern(img, 'no-repeat');
    contextUnder.fillStyle = pattern;
    contextUnder.fillRect(0, 0, width, height);
    // 应用渐变
    contextOver.fillStyle = gradient;
    contextOver.fillRect(0, 0, width, height);
    // 叠加canvas
    contextOver.blendOnto(contextUnder, 'overlay');
    // 给当前context创建pattern
    pattern = context.createPattern(canvasPattern, 'no-repeat');
    // 绘制文本
    context.fillStyle = pattern;
    context.fillText('画布纹理叠加', 0, 60);
};

原理描述:

临时创建一个canvas绘制一个渐变,临时创建一个canvas使用纹理图片填充,两个canvas叠加混合得到新的canvas,然后页面上那个canvas上的文字就把这个叠加混合后canvas作为纹理进行填充,效果即达成。

兼容性

IE9+,Chrome, Safari, Firefox浏览器都支持。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读

android textinput显示不全怎么解决

JavaScript的继承与原型链

The above is the detailed content of Front-end technology realizes text texture overlay. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),