TML5的canvas技术制作网页酷炫效果,可用于网页首页展示效果,增强用户体验!
效果随着你的点击或者鼠标触发即可随时变化闪动的粒子!
实现方法:
html:
css:
js代码:
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()返回画布上的绘图上下文。
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)方法绘制一个“填充”矩形,其中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):在画布上绘制“填充”文本。
strokeText(text,x,y):在画布上绘制文本(轮廓)。
还有许多其他方法旨在帮助在画布上绘制形状和图像。
<canvas> 是HTML中的一个元素,它可被用来通过 JavaScript(Canvas API 或 WebGL API)绘制图形及图形动画。
Canvas API 提供了一个通过 JavaScript 和 HTML 的 <canvas> 元素来绘制图形的方式。它可以用于动画、游戏画面、数据可视化、图片编辑以及实时视频处理等方面。
<canvas>标签本身没有绘图能力,它仅仅是图形的容器。在HTML,一般通过Javascript语言来完成实际的操作。
本文通过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源码:
*请认真填写需求信息,我们会在24小时内与您取得联系。