在网上看到了一个gif图片(图片比较大,加载可能会有些慢),觉得挺有意思的:
于是做为娱乐,顺便试一下Html5的canvas, 仿照上面这个图片,用js写了一个html5版本的(请用支持html5的浏览器查看,如Chrome 、 Firefox 、Safari, IE9以下的版本不支持canvas,所以看不了)
这个程序本身没什么难度,用了几个数学公式,只不过这些东西早忘光了,查了半天资料:-(
主要的两个公式:
极坐标到直角坐标的转换公式
x=rcosθ
y=rsinθ
源代码如下:
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
var canvas;
var ctx;
var rx = 200;
var ry = 200;
var radius = 180;
var sleep = 0;
var count = 0;
function deg2rad(x) {
return x *Math.PI/180;
}
function drawCircle(x, y, r) {
ctx.beginPath();
ctx.arc(x,y,r,0,Math.PI*2,true);
ctx.stroke();
}
function drawLine(x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
if (count++ == 82) {
count = 0;
document.getElementById('redraw').disabled = false;
sleep = 0
}
}
function drawSide(begin1, end1, step1, begin2, step2) {
var d1, d2, x1, y1, x2, y2;
while (begin1 != end1+step1) {;
d1 = deg2rad(begin1);
d2 = deg2rad(begin2);
x1 = rx + radius * Math.cos(d1);
y1 = ry - radius * Math.sin(d1);
x2 = rx + radius * Math.cos(d2);
y2 = ry - radius * Math.sin(d2);
setTimeout('drawLine(' + x1 + ',' + y1 + ',' + x2 + ',' + y2 + ')', sleep*100);
sleep++;
begin1 += step1;
begin2 += step2;
}
}
function drawHeart() {
document.getElementById('redraw').disabled = true;
ctx.clearRect(0,0, canvas.width, canvas.height);
ctx.strokeStyle = "black";
drawCircle(rx, ry, radius, ctx);
ctx.strokeStyle = "red";
drawSide(-90, 0, 4.5, 0, 4.5);
drawSide(-90, -180, -4.5, -180, -4.5);
drawSide(0, 180, 4.5, 90, 9);
}
(function() {
canvas = document.getElementById('heart')
ctx = canvas.getContext('2d')
drawHeart()
})();