练习题1_画布.html 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <style>
  8. #canvas {
  9. /* 背景颜色 */
  10. background-color: black;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <!-- 画布元素 -->
  16. <canvas id="canvas" width="500" height="500"></canvas>
  17. <script>
  18. // 获取元素
  19. var canvas = document.querySelector("#canvas");
  20. // 获取上下文
  21. var ctx = canvas.getContext("2d");
  22. // 设置线的颜色
  23. ctx.strokeStyle = "white";
  24. // 设置线的宽度
  25. ctx.lineWidth = 2;
  26. // 为画布绑定鼠标按下事件
  27. canvas.onmousedown = function (event) {
  28. // 开始绘制 beginPath
  29. ctx.beginPath();
  30. // moveTo 移动到指定位置(落笔点)
  31. ctx.moveTo(event.clientX, event.clientY);
  32. // 绑定鼠标移动事件
  33. canvas.onmousemove = function (e) {
  34. // lineTo 绘制一条线到指定位置
  35. ctx.lineTo(e.clientX, e.clientY);
  36. // stroke 绘制线
  37. ctx.stroke();
  38. }
  39. }
  40. // 为画布绑定鼠标松开事件
  41. canvas.onmouseup = function () {
  42. // 绘制完成,清除鼠标移动事件
  43. canvas.onmousemove = null;
  44. }
  45. </script>
  46. </body>
  47. </html>