Use canvas to achieve barrage effects in videos
This time I will bring you the use of canvas to achieve the barrage effect in videos. What are the precautions for using canvas to achieve the barrage effect of videos? The following is a practical case, let’s take a look.
Recently, I have started to develop a barrage video website, and realized the barrage function through canvas in html5. So don’t talk nonsense, talk about your ideas first and then write the code. Idea: From thepage layout point of view, it is to cover a canvas on the video window generated by the video tag, which can be achieved by using absolute positioning. The most important thing is that js controls the display of barrages on the canvas. Each barrage is packaged into an object. The properties contained in the object include the time when the barrage should appear, the color of the barrage, whether the barrage is moving and the barrage. text. The methods owned by the barrage object include: setting the horizontal and vertical coordinates of the barrage, and the movement function of the barrage. The principle of implementation is to monitor the event of the video starting to play, and generate a timer when the video starts playing. The timer traverses the cyclic barrage object array at every other time and draws the barrage at the appropriate position on the canvas according to the properties of the object. , in addition to the code for drawing the barrage, the timer also contains the code for updating the barrage array.
The picture below is a screenshot of the barrage effect(function () { window.onload=function () { var video = document.getElementsByTagName("video")[0] var cav = document.getElementsByTagName("canvas")[0] //设置常量canvas的高度以及宽度 var cavWidth = 800 var cavHeight = 420 cav.width=cavWidth cav.height=cavHeight var ctx = cav.getContext("2d") //存储弹幕对象的数组 var capObjs = [] var lastItemTime var capHeight = 20 var inputEle = document.getElementsByClassName("caption-input-text")[0] var sendEle = document.getElementsByClassName("caption-sendButton")[0] var colorUl = document.getElementsByClassName("colorItems")[0] var ismoveInputEle = document.getElementsByClassName("caption-input-ismove")[0] //弹幕颜色 var colors=["#fff","#FFCCCC","#CCFFCC","#CCCCFF","#FFFFCC","#CCFFFF"] var selectedColorIndex = 0 var prevPlayTime = 0 //测试数据的数组 var testArrayCopy = [] var capobjId = 0 //弹幕在画布中高度可能值组成的数组 var topObjs = [{blank:true , value : 20 ,index:0}, {blank:true , value : 50 ,index:1}, {blank:true , value : 80 ,index:2}, {blank:true , value : 110 ,index:3}, {blank:true , value : 140 ,index:4}, {blank:true , value : 170 ,index:5}, {blank:true , value : 200 ,index:6}, {blank:true , value : 230 ,index:7}, {blank:true , value : 260 ,index:8}, {blank:true , value : 290 ,index:9}, {blank:true , value : 320 ,index:10}, {blank:true , value : 350 ,index:11}, {blank:true , value : 380 ,index:12}, {blank:true , value : 410 ,index:13}] //test data 测试数据 var testArray = [{content:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",time:"1",ismove:false,colorIndex:0}, {content:"233333333333333",time:"2",ismove:true,colorIndex:0}, {content:"干杯,哈哈哈~~~~~~",time:"2",ismove:true,colorIndex:5}, {content:"干杯,哈哈哈~~~~~~",time:"2",ismove:true,colorIndex:4}, {content:"干杯,哈哈哈~~~~~~",time:"2",ismove:true,colorIndex:4}, {content:"干杯,哈哈哈~~~~~~",time:"2",ismove:true,colorIndex:0}, {content:"干杯,哈哈哈~~~~~~",time:"2",ismove:true,colorIndex:0}, {content:"233333333333333",time:"3",ismove:true,colorIndex:0}, {content:"233333333333333",time:"3",ismove:true,colorIndex:0}, {content:"233333333333333",time:"3",ismove:true,colorIndex:0}, {content:"233333333333333",time:"3",ismove:true,colorIndex:0}, {content:"233333333333333",time:"3",ismove:true,colorIndex:0}, {content:"233333333333333",time:"3",ismove:true,colorIndex:0}, {content:"233333333333333",time:"4",ismove:false,colorIndex:0}, {content:"233333333333333",time:"5",ismove:true,colorIndex:4}, {content:"233333333333333",time:"6",ismove:true,colorIndex:2}, {content:"233333333333333",time:"7",ismove:true,colorIndex:2}, {content:"233333333333333",time:"7",ismove:true,colorIndex:2}, {content:"233333333333333",time:"7",ismove:true,colorIndex:2}, {content:"233333333333333",time:"7",ismove:true,colorIndex:2}, {content:"233333333333333",time:"7",ismove:true,colorIndex:2}, {content:"233333333333333",time:"7",ismove:true,colorIndex:2}, {content:"233333333333333",time:"8",ismove:true,colorIndex:0}, {content:"233333333333333",time:"9",ismove:true,colorIndex:0}, {content:"233333333333333",time:"10",ismove:true,colorIndex:0}, {content:"老师说的非常好,我要好好学习了》》》》",time:"12",ismove:true,colorIndex:0}, {content:"老师说的非常好,我要好好学习了》》》》",time:"13",ismove:true,colorIndex:0}, {content:"老师说的非常好,我要好好学习了》》》》",time:"14",ismove:true,colorIndex:2}, {content:"老师说的非常好,我要好好学习了》》》》",time:"15",ismove:false,colorIndex:0}, {content:"老师说的非常好,我要好好学习了》》》》",time:"16",ismove:true,colorIndex:2}, {content:"老师说的非常好,我要好好学习了》》》》",time:"17",ismove:true,colorIndex:3}, {content:"老师说的非常好,我要好好学习了》》》》",time:"18",ismove:true,colorIndex:2}, {content:"老师说的非常好,我要好好学习了》》》》",time:"19",ismove:true,colorIndex:0}, {content:"老师说的非常好,我要好好学习了》》》》",time:"20",ismove:true,colorIndex:3}, {content:"老师说的非常好,我要好好学习了》》》》",time:"21",ismove:true,colorIndex:0}, {content:"老师说的非常好,我要好好学习了》》》》",time:"22",ismove:true,colorIndex:0}, {content:"老铁们,小礼物走一波了,小汽车小火箭刷起来吧=========",time:"23",ismove:true,colorIndex:0}, {content:"老铁们,小礼物走一波了,小汽车小火箭刷起来吧=========",time:"24",ismove:true,colorIndex:0}, {content:"老铁们,小礼物走一波了,小汽车小火箭刷起来吧=========",time:"25",ismove:true,colorIndex:3}, {content:"老铁们,小礼物走一波了,小汽车小火箭刷起来吧=========",time:"26",ismove:true,colorIndex:0}, {content:"老铁们,小礼物走一波了,小汽车小火箭刷起来吧=========",time:"27",ismove:true,colorIndex:5}, {content:"老铁们,小礼物走一波了,小汽车小火箭刷起来吧=========",time:"28",ismove:false,colorIndex:5}, {content:"老铁们,小礼物走一波了,小汽车小火箭刷起来吧=========",time:"29",ismove:true,colorIndex:5}, {content:"老铁们,小礼物走一波了,小汽车小火箭刷起来吧=========",time:"30",ismove:true,colorIndex:5}, {content:"马上就下课了,瓦罗蓝大陆走起了~~~",time:"31",ismove:true,colorIndex:5}, {content:"马上就下课了,瓦罗蓝大陆走起了~~~",time:"32",ismove:true,colorIndex:2}, {content:"马上就下课了,瓦罗蓝大陆走起了~~~",time:"33",ismove:true,colorIndex:2}, {content:"马上就下课了,瓦罗蓝大陆走起了~~~",time:"33",ismove:true,colorIndex:5}, {content:"马上就下课了,瓦罗蓝大陆走起了~~~",time:"34",ismove:true,colorIndex:5}, {content:"马上就下课了,瓦罗蓝大陆走起了~~~",time:"35",ismove:true,colorIndex:5}, {content:"马上就下课了,瓦罗蓝大陆走起了~~~",time:"36",ismove:true,colorIndex:2}, {content:"马上就下课了,瓦罗蓝大陆走起了~~~",time:"37",ismove:true,colorIndex:2}] //将测试数据备份 copyArray(testArray , testArrayCopy) /*弹幕对象的构造函数,参数分别是:1.ismove:弹幕是否是移动的弹幕,2.spe:弹幕的移动速度,3.col:弹幕的颜色,4.text:弹幕的文本*/ /*原型链方法 setTopValue设置纵坐标,setLeftValue设置横坐标,moving完成坐标的改变,setId完成id值的设置*/ function Caption( ismove , spe , col , text ) { this.isMove = ismove this.speed = spe this.color = col || "#ff0" this.content = text this.latestTime = 0 this.width = text.length * 20 this.id = 0 this.topIndex = 0 this.occupyPos = true this.top = 300 this.left = 0 this.setLeftValue() this.setTopValue() } Caption.prototype.setTopValue = function () { for(var i = 0 ,len = topObjs.length ; i < len ; i++){ if (topObjs[i].blank) { this.top = topObjs[i].value this.topIndex = i topObjs[i].blank = false break } } } Caption.prototype.setLeftValue = function () { if (this.isMove) { this.left = cavWidth } else { var contentLength = this.content.length var nowItemLeft = 420 - contentLength * 9 this.left = nowItemLeft } } Caption.prototype.moving = function () { if (this.isMove) { this.left-=this.speed if ( this.left + this.width < cavWidth && this.occupyPos) { this.occupyPos = false topObjs[this.topIndex].blank = true } } else{ this.latestTime += 1 if (this.latestTime > 450) { topObjs[this.topIndex].blank = true } } } Caption.prototype.setId = function () { this.id = capobjId capobjId++ } var cap1 = new Caption( false , 1 , 0 , "小礼物走一波,双击6666。。。。") capObjs.push(cap1) cap1.setId() //循环遍历数组,根据对象的属性绘制在画布上 function drawAllText () { ctx.clearRect( 0 , 0 , cavWidth , cavHeight) ctx.beginPath() for(var i=0 , len = capObjs . length ; i < len ; i++ ){ ctx.fillStyle = capObjs[i].color ctx.font = "bold 20px Courier New" ctx.fillText( capObjs[i].content , capObjs[i].left , capObjs[i].top ) ctx.closePath() capObjs[i].moving() // if (capObjs[i].left < - cavWidth ) { // capObjs.splice (i ,1) // if excute this statement , will has fault because some item in array is null // solution is : write a new function to refresh the array // } } } //更新数组,当对象已经超出范围的时候从数组删除这个对象 function refreshObjs(objs) { for (var i = objs.length - 1; i >= 0; i--) { if (objs[i].left < - cavWidth || objs[i].latestTime > 450 ) { objs.splice(i , 1) } } } //更新保存弹幕对象的数组 function updateArray () { var now = parseInt( video.currentTime ) for (var i = testArray.length - 1; i >= 0; i--) { var nowItemTime = parseInt(testArray[i].time) if ( nowItemTime == now ) { //首次写的控制高度的方式,空间利用不充分,后来改为setTopValue中的方式 // var nowItemLeft = getLeftValue(testArray[i]) // var diffTime = Math.abs(nowItemTime - lastItemTime) // if (diffTime < 6) { // capHeight += 30 // capHeight = capHeight > 400 ? 20 : capHeight // } var temcolor = colors[testArray[i].colorIndex] var temcap = new Caption ( testArray[i].ismove , 1 , temcolor , testArray[i].content ) capObjs.push(temcap) capObjs[capObjs.length - 1].setId() temcap = null testArray.splice(i,1) } } } //当用户点击send发送弹幕的回调函数 function sendCaption (argument) { var inputEleTxt = inputEle.value var now = parseInt( video.currentTime ) var inputIsmoveValue = ismoveInputEle.checked var temObj = {content:inputEleTxt,time:now,ismove:inputIsmoveValue,colorIndex:selectedColorIndex} testArray.push(temObj) inputEle.value = "" } // function getLeftValue (obj) { // if (obj.ismove) { // return 0 // } // else { // var contentLength = obj.content.length // var nowItemLeft = 420 - contentLength * 9 // return nowItemLeft // } // } //重新启动canvas,用在人为导致进度条时间的改变 function reinitCav (argument) { // testArray = testArrayCopy copyArray(testArrayCopy , testArray) capObjs = [] capHeight = 0 clearInterval(canvasTimer) canvasTimer = null initCanvas() } var canvasTimer = null //初始化canvas,用在开始播放时 function initCanvas () { if (canvasTimer == null ) { canvasTimer = setInterval(function (argument) { drawAllText() updateArray() refreshObjs(capObjs) },10) } }//end function initCanvas //复制数组 function copyArray (arr1 , arr2) { for (var i =0 , len=arr1.length ; i < len ; i++) { arr2[i] = arr1[i] } } //color select event 用户发送弹幕的颜色控制代码 colorUl.addEventListener("click", function( e ){ var prevSelectItemId = "" switch (selectedColorIndex) { case 0: prevSelectItemId = "colorItemFrist" break; case 1: prevSelectItemId = "colorItemSecond" break; case 2: prevSelectItemId = "colorItemThrid" break; case 3: prevSelectItemId = "colorItemFourth" break; case 4: prevSelectItemId = "colorItemFifth" break; case 5: prevSelectItemId = "colorItemSixth" break; default: // statements_def break; } var prevSelectItem = document.getElementById(prevSelectItemId) prevSelectItem.className = "" var eventTarget = e.target eventTarget.className = "selectedColor" var eveTarId = eventTarget.id.substring(9) switch (eveTarId) { case "Frist": selectedColorIndex = 0 break; case "Second": selectedColorIndex = 1 break; case "Thrid": selectedColorIndex = 2 break; case "Fourth": selectedColorIndex = 3 break; case "Fifth": selectedColorIndex = 4 break; case "Sixth": selectedColorIndex = 5 break; default: // statements_def break; } }, false) video.addEventListener("playing" , function () { initCanvas() }) //进度条改变执行代码 video.addEventListener("timeupdate", function () { var nowPlayTime = video.currentTime var diffTime = Math.abs(nowPlayTime - prevPlayTime) prevPlayTime = nowPlayTime if (diffTime > 1) { reinitCav() } }, false) //视频暂停执行代码 video.addEventListener("pause" , function () { clearInterval(canvasTimer) canvasTimer = null }) //点击send的监听事件 sendEle.addEventListener("click" , sendCaption) //input的回车监听事件 inputEle.addEventListener("keydown", function(e) { var keynum = 0 keynum = window.event ? e.keyCode : e.which if (keynum == 13) { sendCaption() } }) var aaaa = function() { alert(1) } aaaa() // function b(aaaa){ // return aaaa() // } // b() }//end })()
H5 implements scalable clock animation
Drag event editor implements drag and drop upload image effect
The above is the detailed content of Use canvas to achieve barrage effects in videos. For more information, please follow other related articles on the PHP Chinese 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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

You may have encountered the problem of green lines appearing on the screen of your smartphone. Even if you have never seen it, you must have seen related pictures on the Internet. So, have you ever encountered a situation where the smart watch screen turns white? On April 2, CNMO learned from foreign media that a Reddit user shared a picture on the social platform, showing the screen of the Samsung Watch series smart watches turning white. The user wrote: "I was charging when I left, and when I came back, it was like this. I tried to restart, but the screen was still like this during the restart process." Samsung Watch smart watch screen turned white. The Reddit user did not specify the smart watch. Specific model. However, judging from the picture, it should be Samsung Watch5. Previously, another Reddit user also reported

With the rise of short video platforms, Douyin has become an indispensable part of everyone's daily life. On TikTok, we can see interesting videos from all over the world. Some people like to post other people’s videos, which raises a question: Is Douyin infringing upon posting other people’s videos? This article will discuss this issue and tell you how to edit videos without infringement and how to avoid infringement issues. 1. Is it infringing upon Douyin’s posting of other people’s videos? According to the provisions of my country's Copyright Law, unauthorized use of the copyright owner's works without the permission of the copyright owner is an infringement. Therefore, posting other people’s videos on Douyin without the permission of the original author or copyright owner is an infringement. 2. How to edit a video without infringement? 1. Use of public domain or licensed content: Public

With the rise of short video platforms, Xiaohongshu has become a platform for many people to share their lives, express themselves, and gain traffic. On this platform, publishing video works is a very popular way of interaction. So, how to publish Xiaohongshu video works? 1. How to publish Xiaohongshu video works? First, make sure you have a video content ready to share. You can use your mobile phone or other camera equipment to shoot, but you need to pay attention to the image quality and sound clarity. 2. Edit the video: In order to make the work more attractive, you can edit the video. You can use professional video editing software, such as Douyin, Kuaishou, etc., to add filters, music, subtitles and other elements. 3. Choose a cover: The cover is the key to attracting users to click. Choose a clear and interesting picture as the cover to attract users to click on it.

Douyin, the national short video platform, not only allows us to enjoy a variety of interesting and novel short videos in our free time, but also gives us a stage to show ourselves and realize our values. So, how to make money by posting videos on Douyin? This article will answer this question in detail and help you make more money on TikTok. 1. How to make money from posting videos on Douyin? After posting a video and gaining a certain amount of views on Douyin, you will have the opportunity to participate in the advertising sharing plan. This income method is one of the most familiar to Douyin users and is also the main source of income for many creators. Douyin decides whether to provide advertising sharing opportunities based on various factors such as account weight, video content, and audience feedback. The TikTok platform allows viewers to support their favorite creators by sending gifts,

1. First open Weibo on your mobile phone and click [Me] in the lower right corner (as shown in the picture). 2. Then click [Gear] in the upper right corner to open settings (as shown in the picture). 3. Then find and open [General Settings] (as shown in the picture). 4. Then enter the [Video Follow] option (as shown in the picture). 5. Then open the [Video Upload Resolution] setting (as shown in the picture). 6. Finally, select [Original Image Quality] to avoid compression (as shown in the picture).

Speaking of ASSASSIN, I believe players will definitely think of the master assassins in "Assassin's Creed". They are not only skilled, but also have the creed of "devoting themselves to the darkness and serving the light". The ASSASSIN series of flagship air-cooled radiators from the appliance brand DeepCool coincide with each other. Recently, the latest product of this series, ASSASSIN4S, has been launched. "Assassin in Suit, Advanced" brings a new air-cooling experience to advanced players. The appearance is full of details. The Assassin 4S radiator adopts a double tower structure + a single fan built-in design. The outside is covered with a cube-shaped fairing, which has a strong overall sense. It is available in white and black colors to meet different colors. Tie

With the popularity of Douyin, more and more people like to share their lives, talents and creativity on this platform. Douyin's 15-second limit makes many users feel that it is not enjoyable enough and hope to extend the video duration. So, how can you extend the video duration on Douyin? 1. Douyin 15 seconds is too short and I want to extend it. How can I extend it? 1. The most convenient way to shoot multiple videos and splice them is to record multiple 15-second videos, and then use the editing function of Douyin to combine them. When recording, make sure to leave some blank space at the beginning and end of each video for later splicing. The length of the spliced video can be several minutes, but this may cause the video screen to switch too frequently, affecting the viewing experience. 2. Use Douyin special effects and stickers Douyin provides a series of special effects

A large model that can automatically analyze the content of PDFs, web pages, posters, and Excel charts is not too convenient for workers. The InternLM-XComposer2-4KHD (abbreviated as IXC2-4KHD) model proposed by Shanghai AILab, the Chinese University of Hong Kong and other research institutions makes this a reality. Compared with other multi-modal large models that have a resolution limit of no more than 1500x1500, this work increases the maximum input image of multi-modal large models to more than 4K (3840x1600) resolution, and supports any aspect ratio and 336 pixels to 4K Dynamic resolution changes. Three days after its release, the model topped the HuggingFace visual question answering model popularity list. Easy to handle
