整合營銷服務商

          電腦端+手機端+微信端=數據同步管理

          免費咨詢熱線:

          HTML5的canvas技術制作網頁酷炫效果

          TML5的canvas技術制作網頁酷炫效果,可用于網頁首頁展示效果,增強用戶體驗!

          效果隨著你的點擊或者鼠標觸發即可隨時變化閃動的粒子!

          實現方法:

          html:

          css:

          js代碼:

          畫布 The <canvas> Element

          The HTML canvas is used to draw graphics that include everything from simple lines to complex graphic objects.The <canvas> element is defined by:

          HTML畫布用于繪制包含從簡單線到復雜圖形對象的所有圖形。

          <canvas>元素定義如下:

          The <canvas> element is only a container for graphics. You must use a script to actually draw the graphics (usually JavaScript).

          <canvas>元素只是圖形的容器。 您必須使用腳本來實際繪制圖形(通常為JavaScript)。

          The <canvas> element must have an id attributeso it can be referred to by JavaScript:

          <canvas>元素必須具有id屬性,因此可以由JavaScript引用:

          getContext() returns a drawing context on the canvas.

          getContext()返回畫布上的繪圖上下文。

          2 坐標系 Canvas Coordinates

          The HTML canvas is a two-dimensional grid.The upper-left corner of the canvas has the coordinates (0,0).X coordinate increases to the right.Y coordinate increases toward the bottom of the canvas.

          3 繪制 Drawing Shapes

          ThefillRect(x, y, w, h) method draws a "filled" rectangle, in which w indicates width and h indicates height. The default fill color is black. A black 100*100 pixel rectangle is drawn on the canvas at the position (20, 20):

          fillRect(x,y,w,h)方法繪制一個&ldquo;填充&rdquo;矩形,其中w表示width,h表示height。 默認填充顏色為黑色。

          畫布上的黑色100 * 100像素矩形繪制在位置(20,20)處:

          The fillStyleproperty is used to set a color, gradient, or pattern to fill the drawing.Using this property allows you to draw a green-filled rectangle.

          fillStyle屬性用于設置顏色,漸變或圖案以填充圖形。

          使用此屬性可以繪制一個綠色填充的矩形。

          The canvas supports various other methods for drawing:

          Draw a LinemoveTo(x,y): Defines the starting point of the line.lineTo(x,y): Defines the ending point of the line.

          Draw a CirclebeginPath(): Starts the drawing.arc(x,y,r,start,stop): Sets the parameters of the circle.stroke(): Ends the drawing.

          GradientscreateLinearGradient(x,y,x1,y1): Creates a linear gradient.createRadialGradient(x,y,r,x1,y1,r1): Creates a radial/circular gradient.

          Drawing Text on the CanvasFont: Defines the font properties for the text.fillText(text,x,y): Draws "filled" text on the canvas.strokeText(text,x,y): Draws text on the canvas (no fill).There are many other methods aimed at helping to draw shapes and images on the canvas.

          畫布支持各種其他繪圖方法:

          畫一條線

          moveTo(x,y):定義行的起始點。

          lineTo(x,y):定義行的終點。

          畫一個圓

          beginPath():啟動繪圖。

          arc(x,y,r,start,stop):設置圓的參數。

          stroke():結束繪圖。

          漸變

          createLinearGradient(x,y,x1,y1):創建線性漸變。

          createRadialGradient(x,y,r,x1,y1,r1):創建一個徑向/圓形漸變。

          在畫布上繪制文字

          字體:定義文本的字體屬性。

          fillText(text,x,y):在畫布上繪制&ldquo;填充&rdquo;文本。

          strokeText(text,x,y):在畫布上繪制文本(輪廓)。

          還有許多其他方法旨在幫助在畫布上繪制形狀和圖像。

          么是Canvas

          <canvas> 是HTML中的一個元素,它可被用來通過 JavaScript(Canvas API 或 WebGL API)繪制圖形及圖形動畫。

          Canvas API 提供了一個通過 JavaScriptHTML<canvas> 元素來繪制圖形的方式。它可以用于動畫、游戲畫面、數據可視化、圖片編輯以及實時視頻處理等方面。

          <canvas>標簽本身沒有繪圖能力,它僅僅是圖形的容器。在HTML,一般通過Javascript語言來完成實際的操作。

          創建HTML頁面并添加繪圖容器

          本文通過Javascript操作Canvas制作一個簡單的顯示當前時間的動畫時鐘,了解和學習簡單的canvas用法,僅以拋磚引玉。

          首先創建一個HTML文件,為了方便管理,使用一個div標簽包裹兩個canvas標簽,并加上一些簡單的css樣式。

          <!doctype html>
          <html lang="zh-cn">
          <head><title>Canvas繪制動畫時鐘</title>
          <style>
          html,body{margin:0;padding:0}
          #clockWrap {
          	position: relative;
          }
          canvas {
          	position: absolute;
          }
          #clock-ui {
          	z-index: 2;
          }
          #clock-plate {
          	z-index: 1;
          }
          </style>
          </head>
          <body>
            <div id="clockWrap">
            <canvas id="clock-plate"></canvas>
            <canvas id="clock-ui"></canvas>
          </div>
          <script></script>
          </body></html>

          本示例中使用了兩個canvas標簽(為什么使用兩個,一個不是更簡單嗎?),一個用于繪制鐘面,一個根據當前時間實時顯示和更新時針、分針和秒針的動態指向。好了,話不多說,開干。

          繪制鐘面刻度

          一個簡單的時鐘,可以分為鐘面上的刻度和指針。其中刻度和12個數字是固定的,我們可以將它們繪制在當作背景的canvas上(示例中id為clock-plate的canvas)。

          (1)要使用canvas,首先必須通過容器獲取渲染上下文:

          var $=function(id){return document.querySelector(id);}//這個函數只是為了方便獲取dom元素
          const canvasbg=$("#clock-plate"),
                canvas=$("#clock-ui"),
                ctx = canvasbg.getContext("2d"),//背景容器上下文
                ctxUI = canvas.getContext("2d");//指針容器上下文,后面代碼要用
          //定義畫布寬度和高度,時鐘圓直徑,并設置畫布大小
          const oW=1000,oH=800,cW=400,r=cW/2,oX=oW/2,oY=oH/2;
          canvas.width=oW;
          canvas.height=oH;
          canvasbg.width=oW;
          canvasbg.height=oH;

          (2)畫鐘的邊框,為了好看,這里畫兩個圈:

           //畫出時鐘外圓框
            ctx.lineWidth = 12;
          	ctx.beginPath();
          	ctx.arc(oX, oY, r+14, 0, 2 * Math.PI);
          	ctx.stroke();
          	ctx.closePath();
          	ctx.lineWidth = 8;
          	//畫出時鐘內圓框(刻度圈)
          	ctx.beginPath();
          	ctx.arc(oX, oY, r, 0, 2 * Math.PI);
          	ctx.stroke();
          	ctx.closePath();
          	ctx.beginPath();

          邊框效果圖

          (3)繪制刻度線和數字,可以利用三角函數計算出每個刻度的坐標:

          利用三角函數計算刻度線的坐標位置

          鐘面上有12個大格,從正上方12開始,它們的度數分別是270,300,330,0,30,60,90,120,150,180,210,240。然后利用JS的Math.sin和Math.cos分別計算出各大格的坐標。注意:js中Math.sin()和Math.cos()的參數不是角度數弧度。可以使用Math.PI/180*角度來轉化,比如將30度轉換成弧度=Math.PI/180*30

          //繪制鐘表中心點
          	ctx.beginPath();
          	ctx.arc(oX, oY, 8, 0, 2 * Math.PI);//圓心
          	ctx.fill();
          	ctx.closePath();
          	//設置刻度線粗細度
          	ctx.lineWidth = 3;
          	//設置鐘面12個數字的字體、大小和對齊方式
          	ctx.font = "30px serif";
          	ctx.textAlign="center";
          	ctx.textBaseline="middle";
          	var kdx,kdy;
          	//繪制12個大刻度和12個數字
          	//為方便計算,先定義了0-11這12個刻度對應的度數,也可以直接定義對應的弧度。
          	const hd=Math.PI/180,degr=[270,300,330,0,30,60,90,120,150,180,210,240];
          	for(var i=0;i<12;i++){
          		kdx=oX+Math.cos(hd*degr[i])*(r-3);
          		kdy=oY+Math.sin(hd*degr[i])*(r-3);
          		ctx.beginPath();
          		ctx.arc(kdx, kdy, 6, 0, 2 * Math.PI);//畫圓形大刻度
          		ctx.fill();
              //繪制刻度對應的數字
          		ctx.strokeText(i==0? 12 : i,oX+Math.cos(hd*degr[i])*(r-24),oY+Math.sin(hd*degr[i])*(r-24));
          		ctx.closePath();
          	}
          	
          	//繪制小刻度
          	ctx.lineWidth = 2;
          	for(var i=0;i<60;i++){
          		if(i % 5 == 0) continue;//跳過與刻度重疊的刻度
          		x0=Math.cos(hd*i*6);
          		y0=Math.sin(hd*i*6);
          		ctx.beginPath();
          		ctx.moveTo(oX+x0*(r-10), oY+y0*(r-10)); 
          		ctx.lineTo(oX+x0*r, oY+y0*r); //畫短刻度線
          		ctx.stroke(); 
          		ctx.closePath();
          	}

          效果如圖:

          鐘面效果圖

          (4)根據當前時間繪制指針

          習慣上,時針粗短,分針略粗而長,秒針細長。為加大區別,示例中秒針細長并且繪制成紅色。

          function drawHp(i){//繪制時針
          	const x0=Math.cos(hd*i*30),y0=Math.sin(hd*i*30);
          	drawPointer(oX,oY,oX+x0*(r-90),oY+y0*(r-90),10,"#000000");
          }
          function drawMp(i){//繪制分針
          	const x0=Math.cos(hd*i*6),y0=Math.sin(hd*i*6);
          	drawPointer(oX,oY,oX+x0*(r-60),oY+y0*(r-60),5,"#000000");
          }
          function drawSp(i){//繪制秒針
          	const x0=Math.cos(hd*i*6),y0=Math.sin(hd*i*6);
          	drawPointer(oX,oY,oX+x0*(r-20),oY+y0*(r-20),2,"#FF0000");
          }
          //抽取出繪制三種指針時共同的部分,注意指針繪制在渲染上下文ctxUI中
          function drawPointer(ox,oy,tx,ty,width,color){
          	ctxUI.strokeStyle = color;
          	ctxUI.lineCap = "round";
          	ctxUI.lineWidth = width;
          	ctxUI.beginPath();
          	ctxUI.moveTo(ox, oy);
          	ctxUI.lineTo(tx,ty);
          	ctxUI.stroke();
          	ctxUI.closePath();
          }

          現在已經有了繪制三種指針的方法,參數是當前時間的時、分和秒,將根據它們的值確定指針的坐標。不過,因為使用的是默認的convas坐標體系,0值實際指向3的位置,需要小小的修正一下。

          window.requestAnimationFrame(function fn(){
          		var d = new Date();
          		ctxUI.clearRect(0,0,oW,oH);
          		//度數從0開始,而0在3刻度(15分/秒位置),修正為全值減15,如果小于0則修正回來
              var hour=d.getHours(),minute=d.getMinutes()-15,second=d.getSeconds()-15;
          		hour=hour>11? hour-15 : hour-3;
          		drawHp(hour>=0? hour : 12+hour);
          		drawMp(minute>=0? minute : 60+minute);
          		drawSp(second>=0? second : 60+second);
          		window.requestAnimationFrame(fn);
          });

          接下來,調用window.requestAnimationFrame,在其中繪制并更新指標的位置。看看效果如何:

          指針繪制情況與實際時間相符

          貌似效果有了,截圖時電腦上的時間是10時17分,指針繪制上,時針指向10時,分針指向17。嗯,感覺有點別扭?對了,時針和分針怎么是端端正正地指向它們的整時整分刻度上呢?實際鐘表上時針和分針是展示動態進度的,此時時針應該越過10時的位置才對。沒關系,我們在繪制時針和分針時別點東西,讓它的角度值加上分針和秒針的值試試。

          //修改后的繪制三種指針的方法
          function drawHp(i,f,m){//繪制時針,參數:時,分,秒
          	const x0=Math.cos(hd*(i+(f/60)+(m/600))*30),y0=Math.sin(hd*(i+(f/60)+(m/600))*30);
          	drawPointer(oX,oY,oX+x0*(r-90),oY+y0*(r-90),10,"#000000");
          }
          function drawMp(i,f){//繪制分針,參數,分,秒
          	const x0=Math.cos(hd*(i+(f/60))*6),y0=Math.sin(hd*(i+(f/60))*6);
          	drawPointer(oX,oY,oX+x0*(r-60),oY+y0*(r-60),5,"#000000");
          }
          function drawSp(i){//繪制秒針
          	const x0=Math.cos(hd*i*6),y0=Math.sin(hd*i*6);
          	drawPointer(oX,oY,oX+x0*(r-20),oY+y0*(r-20),2,"#FF0000");
          }

          再來看看效果,嗯,立竿見影呀:

          指針指向更合理了

          到此為止,canvas繪制一個簡易時鐘就完成了。下面繼續優化一下。剛才使用requestAnimationFrame方法即時更新繪制情況。這個方法與刷新率有關,看看mdn上面怎么說的:

          window.requestAnimationFrame() 方法會告訴瀏覽器你希望執行一個動畫。它要求瀏覽器在下一次重繪之前,調用用戶提供的回調函數。

          對回調函數的調用頻率通常與顯示器的刷新率相匹配。雖然 75hz、120hz 和 144hz 也被廣泛使用,但是最常見的刷新率還是 60hz(每秒 60 個周期/幀)。為了提高性能和電池壽命,大多數瀏覽器都會暫停在后臺選項卡或者隱藏的 <iframe> 中運行的 requestAnimationFrame()。

          本示例中,更新指針的位置并不需要很高的刷新頻率,可以通過節流進行一下優化:

          var fps = 5, fpsInterval = 1000 / fps,lastTime = new Date().getTime(); //記錄上次執行的時間
          function runStep() {
              requestAnimationFrame(runStep);
              var d=new Date(),now = d.getTime()
              var elapsed = now - lastTime;
              if (elapsed > fpsInterval) {
          				ctxUI.clearRect(0,0,oW,oH);
                  lastTime = now - (elapsed % fpsInterval); 
          			//度數從0開始,而0在3刻度(15分/秒位置),修正為全值-15,如果小于0則用60減回
                  var hour=d.getHours(),minute=d.getMinutes()-15,second=d.getSeconds()-15;//console.log(d.getSeconds(),second);
                  hour=hour>11? hour-15 : hour-3;
                  drawHp(hour>=0? hour : 12+hour,minute+15,second+15);
                  drawMp(minute>=0? minute : 60+minute,second+15);
                  drawSp(second>=0? second : 60+second);
              }
          }
          runStep();

          當然,實現時鐘的方法是很多,比如可以使用畫布的旋轉(rotate方法)來實現指針的動態轉動等等。

          完整HTML+JS源碼:


          主站蜘蛛池模板: 亚洲国产欧美国产综合一区 | 少妇激情AV一区二区三区| 国产精品va无码一区二区| 无码人妻精品一区二区三区99不卡| 亚洲制服中文字幕第一区| 制服中文字幕一区二区 | 日本福利一区二区| 亚洲一区二区三区在线| 无码一区二区三区在线观看| 国产一区二区三区高清在线观看| 无码人妻av一区二区三区蜜臀| 国产精品久久一区二区三区| 无码av免费一区二区三区试看 | 国产高清一区二区三区视频| 亚洲精品无码一区二区| 精品一区二区三区在线播放视频| 亚洲AV无码一区二区三区系列| 内射女校花一区二区三区| 国产精品一区12p| 国产在线视频一区二区三区98| 国产午夜精品一区二区三区不卡| 一区二区三区91| 99久久精品费精品国产一区二区| 亚洲国产一区视频| 日韩AV无码一区二区三区不卡毛片| 成人乱码一区二区三区av| 久久婷婷色综合一区二区| 国产精品无圣光一区二区 | 成人国产精品一区二区网站公司| 日本无卡码一区二区三区| 久久精品日韩一区国产二区| 成人毛片无码一区二区| 无码国产亚洲日韩国精品视频一区二区三区| 国产萌白酱在线一区二区| 午夜无码视频一区二区三区| 国产午夜精品一区二区三区不卡| 久久久久久人妻一区精品| 国产精品制服丝袜一区| 激情爆乳一区二区三区| 亚洲无人区一区二区三区| 精品一区精品二区制服 |