歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 用HTML5的Canvas寫字的例子

用HTML5的Canvas寫字的例子

日期:2017/3/1 11:08:07   编辑:Linux編程

最近項目輕松了一些,就抱著學習的態度閱讀了HTML Canvas 2D Context的內容。又想到以前曾經在Android上做過原筆跡手寫的內容,就想試著在HTML5中簡單做一下看看。摸索著完成了demo。下面是在Google Chrome 13.0版本上的效果。

下面附上代碼,僅僅為學習,沒做優化,作為例子吧。

注:要在支持HTML5的浏覽器上運行才能看到效果。

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

Copyright © Linux教程網 All Rights Reserved