没想到啊

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

用HTML5的Canvas写字的例子

http://www.oschina.net/code/snippet_85011_7202

DEMO: http://lovebook.sinaapp.com/brush/

 1 <html>  
2 <head>
3 <title>write demo</title>
4 </head>
5 <body>
6 <canvas width="800" height="450" style="border:1px solid black"></canvas>
7 <div id="info">-</div>
8 <script>
9 var canvas = document.getElementsByTagName('canvas')[0];
10 canvas.addEventListener('mousemove', onMouseMove, false);
11 canvas.addEventListener('mousedown', onMouseDown, false);
12 canvas.addEventListener('mouseup', onMouseUp, false);
13
14 var info = document.getElementById('info');
15 var context = canvas.getContext('2d');
16 var linex = new Array();
17 var liney = new Array();
18 var linen = new Array();
19
20 var lastX = -1;
21 var lastY = -1;
22 var hue = 0;
23 var flag = 0;
24
25 function onMouseMove(evt) {
26 if (flag == 1) {
27 linex.push(evt.layerX);
28 liney.push(evt.layerY);
29 linen.push(1);
30 context.save();
31 context.translate(context.canvas.width/2, context.canvas.height/2);
32 context.translate(-context.canvas.width/2, -context.canvas.height/2);
33 context.beginPath();
34 context.lineWidth = 5 + Math.random() * 10;
35
36 for (var i=1;i<linex.length;i++) {
37 lastX = linex[i];
38 lastY = liney[i];
39 if (linen[i] == 0) {
40 context.moveTo(lastX,lastY);
41 } else {
42 context.lineTo(lastX,lastY);
43 }
44 }
45
46 huehue = hue + 10 * Math.random();
47 context.strokeStyle = 'hsl(' + hue + ', 50%, 50%)';
48 context.shadowColor = 'white';
49 context.shadowBlur = 10;
50 context.stroke();
51 context.restore();
52 }
53 info.firstChild.nodeValue ='x = ' + evt.layerX + ' y = ' + evt.layerY;
54 }
55 function onMouseDown(evt) {
56 flag = 1;
57 linex.push(evt.layerX);
58 liney.push(evt.layerY);
59 linen.push(0);
60 }
61 function onMouseUp(evt) {
62 flag = 0;
63 linex.push(evt.layerX);
64 liney.push(evt.layerY);
65 linen.push(0);
66 }
67 </script>
68 </body>
69 </html>



posted on 2011-11-25 11:05  没想到啊  阅读(708)  评论(0)    收藏  举报