HTML5的canvas标签用于绘制图像(通过脚本,通常是 JavaScript)。不过,canvas元素本身并没有绘制能力(它仅仅是图形的容器)必须使用脚本来完成实际的绘图任务。
下面,具体总结了一下使用画布canvas的步骤:
画布:
canvas
在页面上规划出一块空间,canvas标签,通过javascript控制画布完成绘制
1.获取画布
1
|
var canvas=document.getElementById( "" ); |
2.获取上下文对象 (获取画笔)
1
|
var cx=canvas.getContext(“2d”); |
3.设置画笔样式
1
2
|
cx.fillStyle=‘red '; cx.strokeStyle=‘blue' ; |
4.开始绘制
下面是对于canvas使用,绘制一个简单钟表的小例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >Document</ title > < script > window.onload=function(){ //1.获取画布 var canvas=document.getElementById("canvas"); //2.获取画笔 var cx=canvas.getContext("2d"); function clock(){ //3.设置画笔样式 cx.fillStyle="orange"; //4.绘制图形 //绘制表盘 cx.beginPath(); cx.arc(300,300,200,0,Math.PI*2) cx.closePath(); cx.fill(); //绘制时刻度 cx.lineWidth=2; cx.strokeStyle="black"; for(var i=0;i< 12 ;i++){ cx.save(); cx.translate(300,300); cx.rotate(i*(Math.PI/6)); // cx.beginPath(); cx.moveTo(0,-180); cx.lineTo(0,-200); // cx.closePath(); cx.stroke(); cx.fillStyle = "black" ; cx.font = "16px blod" ; cx.rotate(Math.PI/6) cx.fillText(i+1,-5,-220); cx.restore(); } //绘制分刻度 for(var i = 0 ;i<60;i++){ cx.save(); cx.translate(300,300); cx.rotate(i*(Math.PI/30)); cx.beginPath(); cx.moveTo(0,-190); cx.lineTo(0,-200); cx.closePath(); cx.stroke(); cx.restore(); } //获取当前时间 var today = new Date(); var hour = today .getHours(); var min = today .getMinutes(); var sec = today .getSeconds(); hour =hour+min/60; //绘制时针 cx.lineWidth = 5 ; cx.save(); cx.beginPath(); cx.translate(300,300); cx.rotate(hour*(Math.PI/6)); cx.moveTo(0,10); cx.lineTo(0,-100); cx.closePath(); cx.stroke(); cx.restore(); //绘制分针 cx.lineWidth = 3 ; cx.save(); cx.beginPath(); cx.translate(300,300); cx.rotate(min*(Math.PI/30)); cx.moveTo(0,10); cx.lineTo(0,-120); cx.closePath(); cx.stroke(); cx.restore(); //绘制秒针 cx.lineWidth = 1 ; cx.strokeStyle = "red" ; cx.save(); cx.beginPath(); cx.translate(300,300); cx.rotate(sec*(Math.PI/30)); cx.moveTo(0,10); cx.lineTo(0,-160); cx.closePath(); cx.stroke(); cx.restore(); //绘制交叉处 cx.fillStyle = "#ccc" ; cx.strokeStyle = "red" ; cx.save(); cx.translate(300,300); cx.beginPath(); cx.arc(0,0,5,0,Math.PI*2); cx.closePath(); cx.fill(); cx.stroke(); cx.restore(); setTimeout(clock,1000); } clock() } </script> </ head > < body > < canvas id = "canvas" width = "600px" height = "600px" style = "background-color: #ccc;" ></ canvas > </ body > </ html > |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_44359232/article/details/108506676