Summary of methods to achieve barrage effect (css and canvas)
This article mainly introduces a summary of the methods to achieve the barrage effect (css and canvas). It has a certain reference value. Now I share it with you. Friends in need can refer to it.
I posted it before in a In the lottery page on the mobile terminal, the display window of the lottery results needs to be displayed in a barrage carousel. I have gone through some pitfalls before, and now I will summarize how to achieve the front-end barrage effect.
css3 realizes the beggar’s version of barrage
css3 barrage performance optimization
canvas realizes barrage
canva barrage’s extended function
1. CSS3 realizes the beggar’s version of barrage
(1) How to realize barrage through css3
First let’s look at how to realize the simplest barrage through css method The barrage:
First define the dom structure of a barrage in HTML:
<p>我是弹幕</p>
The movement of the barrage can be achieved by moving this block, so that the barrage moves from right to left For example, the initial position of the barrage is on the leftmost side of the container and the edge is hidden (the leftmost side of the barrage fits the rightmost side of the container). This can be achieved by absolute positioning and transform:
.block{ position:absolute; }
Initial Position:
from{ left:100%; transform:translateX(0) }
The end position when moving to the far left is (the rightmost part of the barrage fits the leftmost part of the container):
to{ left:0; transform:translateX(-100%) }
The specific illustrations of the starting position and the ending position are as follows Shown:
A complete two-frame barrage animation can be defined based on the starting position and end position:
@keyframes barrage{ from{ left:100%; transform:translateX(0); } to{ left:0; transform:translateX(-100%); } }
Give the bullet Introduce this animation into the screen element:
.block{ position:absolute; /* other decorate style */ animation:barrage 5s linear 0s; }
In this way, you can achieve a beggar version of the barrage effect:
(2) Pass Defects of absolute positioning and left barrage implementation
First clarify the css rendering process
I) Generate a DOM tree based on the structure of HTML (the DOM tree includes display :none node)
II) Based on the DOM tree, generate a render tree based on the geometric attributes of the node (margin/padding/width/height/left, etc.)
III) Continue to render attributes such as color and font based on the render tree
What will happen if the attributes in I) and II) change reflow (reflow), if only the properties in III) change, only repaint (redraw) will occur. Obviously we can also see from the CSS rendering process: reflow must be accompanied by redrawing.
reflow (reflow): When part or all of the render tree changes due to size, margin, etc., the process that needs to be rebuilt is called reflow
repaint (redraw): when some attributes of the element change , if the appearance background color does not cause layout changes and needs to be re-rendered, it is called redraw
reflow (reflow) will affect the rendering speed of the browser css, so when optimizing web page performance, it is necessary to reduce the number of reflows occur.
In the first section, we used the left attribute to achieve the effect of barrage. Left will change the layout of the element, so reflow will occur, which will cause barrage animation on the mobile page. Stuck and stopped.
2. CSS3 barrage performance optimization
We found out that the barrage animation in the first section has a stuck problem. Let’s see how to solve the animation problem. Stuck and stopped.
(1) CSS turns on hardware acceleration
Use CSS to turn on hardware acceleration in the browser, and use GPU (Graphics Processing Unit) to improve web page performance. In view of this, we can use the power of the GPU to make our website or application perform more smoothly.
CSS animations, transforms and transitions do not automatically turn on GPU acceleration, but are performed by the browser's slow software rendering engine. So how can we switch to GPU mode? Many browsers provide certain triggered CSS rules.
The more common way is that we can turn on hardware acceleration through 3d changes (translate3d attribute). In view of this, we modify the animation to:
@keyframes barrage{ from{ left:100%; transform:translate3d(0,0,0); } to{ left:0; transform:translate3d(-100%,0,0); } }
In this way, we can turn on hardware acceleration , optimize web page performance. However, this method does not fundamentally solve the problem. At the same time, using the GPU increases memory usage, which will reduce the battery life of the mobile device and so on.
(2) Do not change the left attribute
The second method is to find a way not to change the value of the left attribute before and after the barrage animation, so that reflow will not occur.
We want to determine the initial position of the barrage node only through translateX, but translateX(-100%) is relative to the barrage node itself, not to the parent element, so we couple js and css, Get the width of the parent element where the barrage node is located in js, and then define the initial position of the barrage node based on the width.
Take the parent element as body as an example:
//css .block{ position:absolute; left:0; visibility:hidden; /* other decorate style */ animation:barrage 5s linear 0s; } //js let style = document.createElement('style'); document.head.appendChild(style); let width = window.innerWidth; let from = `from { visibility: visible; -webkit-transform: translateX(${width}px); }`; let to = `to { visibility: visible; -webkit-transform: translateX(-100%); }`; style.sheet.insertRule(`@-webkit-keyframes barrage { ${from} ${to} }`, 0);
In addition to coupling js to calculate the width of the parent element to determine the initial position of the barrage node, here in the barrage node we In order to prevent the initial position from being displayed, the visibility:hidden attribute is added. Prevent barrage nodes from being displayed in the parent container before the initial position is determined. The barrage will only become visible if it starts scrolling from its initial position.
但是这种css的实现方式,在实现弹幕的扩展功能方面比较麻烦,比如如何控制弹幕暂停等等。
3. canvas实现弹幕
除了通过css实现弹幕的方法之外,通过canvas也可以实现弹幕。
通过canvas实现弹幕的原理就是时时的重绘文字,下面来一步步的实现。
-
获取画布
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d'); 绘制文字
ctx.font = '20px Microsoft YaHei'; ctx.fillStyle = '#000000'; ctx.fillText('canvas 绘制文字', x, y); 上面的fillText就是实现弹幕效果的主要api,其中x表示横方向的坐标,y表示纵方向的坐标,只要时时的改变x,y进行重绘,就可以实现动态的弹幕效果。
-
清除绘制内容
ctx.clearRect(0, 0, width, height);
具体实现
通过定时器,定时改变x,y,每次改变之前先进性清屏,然后根据改变后的x,y进行重绘。当存在多条弹幕的情况下,定义:
let colorArr=_this.getColor(color); 弹幕数组多对应的颜色数组 let numArrL=_this.getLeft(); 弹幕数组所对应的x坐标位置数组 let numArrT=_this.getTop(); 弹幕数组所对应的y坐标位置数组 let speedArr=_this.getSpeed(); 弹幕数组所对应的弹幕移动速度数组
定时的重绘弹幕函数为:
_this.timer=setInterval(function(){ ctx.clearRect(0,0,canvas.width,canvas.height); ctx.save(); for(let j=0;j<barragelist.length><p>实现的效果为:</p> <p><span class="img-wrap"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn//upload/image/655/667/209/1532493329346452.gif?x-oss-process=image/resize,p_40" class="lazy" title="1532493329346452.gif" alt="Summary of methods to achieve barrage effect (css and canvas)"></span></p> <h2 id="canva弹幕的扩展功能">4. canva弹幕的扩展功能</h2> <p>通过canvas实现弹幕的方式,很方便做比如暂停弹幕滚动等扩展功能,此外,也可以给弹幕增加头像,给每条弹幕增加边框等等功能,以后再补充。</p> <p>相关推荐:</p> <p><a href="http://www.php.cn/html5-tutorial-406922.html" target="_blank" title="H5微信支付之引入微信的js-sdk包失败的解决方法">H5微信支付之引入微信的js-sdk包失败的解决方法</a></p> <p><a href="http://www.php.cn/html5-tutorial-406614.html" target="_blank" title="使用h5 canvas实现时钟的动态效果">使用h5 canvas实现时钟的动态效果</a></p> <div></div></barragelist.length>
The above is the detailed content of Summary of methods to achieve barrage effect (css and canvas). For more information, please follow other related articles on the PHP Chinese website!

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

"h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.

H5, or HTML5, is the fifth version of HTML. It provides developers with a stronger tool set, making it easier to create complex web applications. The core functions of H5 include: 1) elements that allow drawing graphics and animations on web pages; 2) semantic tags such as, etc. to make the web page structure clear and conducive to SEO optimization; 3) new APIs such as GeolocationAPI support location-based services; 4) Cross-browser compatibility needs to be ensured through compatibility testing and Polyfill library.

How to create an H5 link? Determine the link target: Get the URL of the H5 page or application. Create HTML anchors: Use the <a> tag to create an anchor and specify the link target URL. Set link properties (optional): Set target, title, and onclick properties as needed. Add to webpage: Add HTML anchor code to the webpage where you want the link to appear.

Solutions to H5 compatibility issues include: using responsive design that allows web pages to adjust layouts according to screen size. Use cross-browser testing tools to test compatibility before release. Use Polyfill to provide support for new APIs for older browsers. Follow web standards and use effective code and best practices. Use CSS preprocessors to simplify CSS code and improve readability. Optimize images, reduce web page size and speed up loading. Enable HTTPS to ensure the security of the website.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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

SublimeText3 Chinese version
Chinese version, very easy to use

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),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function