Recently, I started developing barrage video websites, and achieved the function of barrage through Canvas in HTML5.
Then don't talk about gossip, let's talk about thinking first.
Idea: From the page layout, it covers a canvas on the video window generated by the Video tag, and it can be achieved with absolute positioning. The most important thing is the display of the barrage on the js control canvas. Each barrage is packaged as an object. The attributes contained in the objects have the time when the barrage should appear, the color of the barrage, whether the barrage is moved and the barrage is the barrage. Text. The barrage object has methods include: set the horizontal vertical coordinates of the barrage, the movement of the barrage. The principle of implementation is the event where the listening video starts to play, and a timer is generated when the video starts. The timer traverses the circular barrage object array and according to the attributes of the object every one time. In addition to drawing the code of the barrage, the timer also has the code for updating the bullet array.
The picture below is a screenshot of the barrage effect
Then start the code directly:
(Function () {Window.OnLoad = Function () {var video = document.GetelementsBytagname (video) [0] VAR CAV = Document.GetelementsBytagname (Canvas) [0] // Set the height and width of the constant CANVAS VAR Cavwidth = 800 Var Cavheight = 420 Cav.width = Cavwidth Cav.height = Cavheight Var CTX = Cav.getContext (2D) // The array of storage barrage object VAR CAPOBJS = [] VAR LastItemtime Var Eight = 20 var INPutele = Document.GetelementsByClassName (CAPTION -INPUT-TEXT) [0] VAR SENDELE = DOCUMENT.GetelementsByClassName (CAPTION-Sendbutton) [0] VAR colorm = document.GetelementsByClassName (ColorItems) [0] AR ismoveinputele = Document.GetelementsByClassName (CAPTION-Input-Ismove) [0] // The barrage color var colors = [#FFF,#FFCCCC,#CCFFCC,#CCCCFF,#FFFFCC,#CCFFFFF] VAR SelectColorindex = 0 VAR Prevplaytime = 0 // Test data. y = [] var capobjid = 0 // The array of versatiles in the canada in the canvas varitobjs = [{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 test data var testarray = [{content: abcdefghijklmnopqrstuvwxyz, time: 1, ismove: false, colorINDEX: 0}, {conne, TENT: 233333333333333, Time: 2, Ismove: True, ColorIndex: 0}, {Content: Dry, Hahaha ~~~~~~, Time: 2, Ismove: TRUE, ColorINDEX: 5}, {Content: Dry, Hahaha ~~~~~ Time: 2, ismove: true, colorindex: 4}, {content: dry toast, hahaha ~~~~~~, time: 2, ismove: true, colorIndex: 4}, {content: dry toast, hahaha ~~~ ~~~, Time: 2, ISMove: True, ColorIndex: 0}, {Content: dry toast, hahaha ~~~~~, 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: T: T Rue, colorindex: 0}, {content : 2333333333333333, Time: 3, ISMOVE: TRUE, ColorIndex: 0}, {content: 2333333333, Time: 3, ISMove: True, colorIndex: 0}, {content: 233333333333333 3333, time: 3, ismove: true, colorIndex: 0 }, {Content: 2333333333333333, Time: 4, ISMOVE: False, ColorIndex: 0}, {CO NTENT: 23333333333333, Time: 5, ISMOVE: TRUEX: 4}, {conference: {conference: 2333333333333333, Time: 6, ISMOVE: TRUE , ColorInDex: 2}, {Content: 233333333333333, Time: 7, Ismove: True, ColorIndex: 2}, {Content: 23333333333333, Time: 7, ISMOVE: TRUE, COLORIRINDEX: 2 }, {Content: 233333333333333, Time: 7 , ismove: true, colorIndex: 2}, {Content: 233333333333333, Time: 7, ISMOV E: True, colorindex: 2}, {content: 233333333333333, Time: 7, ISMOVE: TRUE: TRUE , ColorIndex: 2}, {Content: 233333333333333 , Time: 7, ISMOVE: True, ColorINDEX: 2}, {Content: 233333333333333, Time: 8, ISMOVE: TRUE, ColorINDEX: 0}, {Content: 233333333333333, Time: 9, ISM OVE: true, colorindex: 0}, {Content: 233333333333333, Time: 10, ISMOVE: True, ColorIndex: 0}, {Content: The teacher said very well, I want to study hard "," ", is: 12, ismove: true, colorindex: 0}, {content:老师说的非常好,我要好好学习了》》》》,time:13,ismove:true,colorIndex:0},{content:老师说的非常好,我要好好学习了》》》》 , Time: 14, ISMove: True, ColorINDEX: 2}, {Content: The teacher said very well, I want to study hard "" "" "", is: 15, ismove: false, colorIndex: 0}, {content: teacher: teacher Said very well, I want to study hard "" "" "" ", 16, ismove: true, colorIndex: 2}, {content: the teacher said very well, I want to study" "" "" , ismove: true, colorindex: 3}, {content: The teacher said very well, I want to study hard "" "" ", Time: 18, ismove: true, colorIndex: 2}, {content: The teacher said very well , I want to study hard "" "" ", time: 19, ismove: true, colorInDex: 0}, {content: the teacher said very well, I want to study well" "" "", 20, ismove: true: true: true: true: true: true: true: true: true: true: true: true: true: true: true: true: true: true: true: true: true: true: true: true , ColorIndex: 3}, {Content: The teacher said very well, I want to study hard "" "" "", time: 21, ismove: true, colorIndex: 0}, {conference: the teacher said very well, I want to be good, I want to be good. Study "" "" "", Time: 22, ismove: true, colorindex: 0}, {content: old iron, small gifts have taken a wave, the small rocket is brushed ========= , Time: 23, ISMOVE: TRUE, ColorINDEX: 0}, {Content: Old Iron, the small gifts have taken a wave, the small rockets are brushed ================== : true, colorindex: 0}, {content: old iron, small gifts have taken a wave, small car rockets brush up =======, time: 25, ismove: true, colorindex: 3: 3 }, {Content: Old iron, the small gifts have taken a wave, the small rockets are brushed =========, time: 26, ismove: true, colorindex: 0}, {content: old: old Iron, small gifts have taken a wave, the small rockets of the car are brushed =========, time: 27, ismove: true, colorIndex: 5}, {content: old iron, small gifts go It's a wave, the small car rocket brush it ================================================================================================================================================, ISMOVE: False: 5}, {Content: Old iron, the small gifts have taken a wave, the car is the car, the car is the car, the car is the car, the car is the car, the car is the car Small rockets to brush ========================================================================================================================================================================, ISMOVE: TRUTEX's Old Rocketing ========, time: 30, ismove: true, colorIndex: 5}, {content: immediately after class, Varo Lan is going up ~~~, time: 31, ismove: true, colorIndex : 5}, {Content: I'm going to class right away, Varo Blue continent is getting up ~~~, Time: 32, ismove: true, colorIndex: 2}, {content: immediately after class, Varo Blue continent goes up and gets up. It's ~~~, time: 33, ismove: true, colorIndex: 2}, {Content: immediately after class, Varo Blue Continental gets up ~~~, Time: 33, ismove: true, colorIndex: 5}, {Content: It's out of class right away, and Varo Lan has gone. , Time: 35, ISMOVE: TRUE, ColorINDEX: 5}, {Content: I will go to get out of class right away, Varo Blue continent is getting up ~~~, Time: 36, ismove: true, colorIndex: 2}, {content: right away: Immediately After class, the Varo Lan mainland came up ~~~, Time: 37, ISMOVE: TRUE, ColorIndex: 2}] // Back the test data (testArray, TestAraycopy) /*Barbite objects, parameters, parameters, parameters They are: 1.ISMOVE: Whether the barrage is the mobile barrage, 2.Spe: the movement speed of the barrage, 3.Col: the color of the barrage, 4.text: the text of the barrage* / /*prototype chain method SettopValue sets the vertical coordinates, the SetleFTVALUE sets the horizontal coordinate, the MOVING completes the coordinate change, setid completes the ID value setting*/ function capption (ISMove, SPE, COL, Text) {this.ismove = iSmove this. .speed = SPE this.Color = Col || #ff0 This.Content = Text this.latedtime = 0 this.width = text.length * 20 this.id = 0 this.topindex = 0 this.occupypos = true this.top = 300 this.Left = 0 This .setValue () this.SettopValue ()} Caption.prototype.Settopvalue = Function () {for (var I = 0, Len = Topobjs.Length; I <len; I ++) {if (Topo bjs [i] .blank) { this.top = topObjs [i]. Value this.topindex = i TopObjs [i] .blank = False Break}} caption.prototype.SetLeftValue = Function () {if (this.is.is.is.is Move) {this.Left = cavwidth} Else {var contentLength = this.Content.Length Var NowItemleft = 420 -ContentLength * 9 This.Left = NowItemleft}} CaPTION. Moving = Function () {if (this.ismove) {this.left- = this.speed if (this.Left + this.Width <cavwidth &&OCCUPYPOS) {this.occupypos = false topobjs [this.topindex] .blank = true}} Time += 1 if (this.latesttime> 450) {TopObjs [this.topindex] .blank = TRUE}}} cappion.prototype.Setid = Function () {This.id = Capobjid Capobjid ++} VAR CAP1 = New Capting (F. Alse, 1, 0, small gifts take a wave, double -click 6666. Essence Essence Essence ) CAPOBJS.Push (CAP1) CAP1.Setid () // Circle the array and draw the function drawallText () {ctx.Clearrect (0, 0, Cavheighth, Cavheight) according to the attributes of the object. for (for (for (for (for (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, CA pobjs [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 becaue it item in array is null // solution is: write a new function to refresh the array //}} // update the array, the object is already super super super Delete this from an array when it comes out Object function refreshobjs (objs) {for (var I = Objs.length -1; i> = 0; i-) {if (ibjs [i] .let < -cavwidth || objs [i] .Latesttime> 450) {Objs.splice (i, 1)}}} // Update the array of the array of the barrage object function, ; I-) {var newItemtime = PARSEINT (testarray [i] .time) if (nowItemtime == Now) {// The first control height of the control was not sufficient, and then the way of space in settopvalue // Var NowItemleft = GetleFTVALUE (TestArray [i]) // VAR DIFFTIME = Math.abs (nowItemtime -LastITEMTIME) // if (DIFFTIME <6) {// CAPHEIGHT += 30 // CAPH Eight = CAPHEIGHT> 400? 20: CAPHEIGHT / /} VAR TEMCOLOR = COLORS [TESTARRAY [I] .colorIndex] varge Temcap = New Caption (Testarray [i] .smove, Temcolor, TESTARRAY [i] .content) ) Capobjs [capobjs.Length- 1] .setID () Temcap = NULL TESTARRAY.Splice (i, 1)}} // When the user clicks the callback function of Send SendCaption (argument) {Var InputEletxt = InputEle.value Var w = PARSEINT (Video .currenttime) Var inputISMOVALUE = ISMOVEINPUTELE.Checked VAR TEMOBJ = {Content: InputEletxt, Time: NOW, ISMOVE: InputISMOVALUE, COLORORINDEX: s ElectedColorIndex} testarray.push (temObj) inputle.value =} // function getleftValue (obj) {// if (obj.ismove) {// Return 0 //} // Else {// var contactlength = obj.content.Length // var notemleft = 420 -ContentLength * 9 // Return nowited //} //} // /} // Restart Canvas to change the Function Reinitcav (ARGUMENT) {// Testarray Copyarray (TESTARAYCOPY, TESTARRAY) CAPHEIGHT = 0 0 0 Clearinterval (Canvastimer) Canvastimer = NULL Initcanvas ()} Var Canvastimer = NULL // Initialize Canvas, when starting to play, the function initiated initcanvas () {if (Canvastimer == NULL) {Canvastimer = SetInterval (ARGUMENT) {DRAWALLTEXT () Updatearrr ay () RefreshObjs (capobjs)}, 10)}} // End Function Initcanvas // Copy the array Function CopyArray (ARR1, ARR2) {for (var I = 0, Len = Arr1.Length; I <Len; I ++) {ARR2 [i] = Arr1 [i]} // Color Select Event user sends the color control code of the barrage. Emid = colorItemfrist break; case 1: prevselectIDEMID = colorItemsecond break; case 2: PrevSelectIDEMID = COLORORITEMTHRID BREAK; Case 3: PrevSelectITEMID = COLORORITEMFOUNFOURTH BREAK; CASE 4: PrevSelectIDID = COLORORITEMFIFIFIFTH BREAK; CASE 5: PrevSelegIDID = COLORORTEMSIXTH BREAK; default: // statements_def Break;} Var PrevSelectITEM = DOCUMENT.GetelementByid (PrevSelectID) e = var EventTarget = E.Target EventTarget.className = SelectColor Var Evetarid = EventTarget.Substring (9) Switch (EVetarid) {Case Frist: SelectedColorinde x = 0 Break; Case Second: SelectedColorindex = 1 Break; Case Thrid: SelectedColorindex = 2 Break; Case FourTh: SELECTEDCOLORORIRINDEX = 3 Break; Case Fifth: SelectedColorindex = 4 Break; Case SiXTH: SelectedColorindex = 5 BREAK; DEFAULT: // F BREAK;}}, False) Video.addeventListener (Playing, Function () {Initcanvas ()} ) // Progressive strip changes the execution code video.addeventListener (timeupdate, function () {var nowplaytime = video.currenttime var diftime = math.abs (nowplaytime-s me) PrevplayTime = Nowplaytime if (Difftime> 1) {Reinitcav ()}} , FALSE) // Video suspension of execution code video.addeventListener (PAUSE, FUNCTION () {Clearinterval (Canvastimer) Canvastimer = NULL}) CK, Sendcaption) // Input Enter monitoring Incident Inputdele.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})
I hope to be able to help students who want to make a barrage, you can also go to github to download the complete project code: gitbub project address
The above is all the contents of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support VEVB Wulin.com.