重构版本:https://www.geekai.net.cn/drawing-board/web/index.html
image.png

开始画线

搜索canvas 教程MDN
我们使用CRM学习法
js代码如下:

  1. let canvas = document.getElementById("canvas");
  2. canvas.width = document.documentElement.clientWidth;
  3. canvas.height = document.documentElement.clientHeight;
  4. let ctx = canvas.getContext("2d");
  5. ctx.fillStyle = "black";
  6. ctx.strokeStyle = "none";
  7. ctx.lineWidth = 8;
  8. ctx.lineCap = "round";
  9. let painting = false;
  10. let last;
  11. var isTouchDevice = "ontouchstart" in document.documentElement;
  12. if (isTouchDevice) {
  13. canvas.ontouchstart = (e) => {
  14. let x = e.touches[0].clientX;
  15. let y = e.touches[0].clientY;
  16. last = [x, y];
  17. };
  18. canvas.ontouchmove = (e) => {
  19. let x = e.touches[0].clientX;
  20. let y = e.touches[0].clientY;
  21. drawLine(last[0], last[1], x, y);
  22. last = [x, y];
  23. };
  24. } else {
  25. canvas.onmousedown = (e) => {
  26. painting = true;
  27. last = [e.clientX, e.clientY];
  28. console.log(last);
  29. };
  30. canvas.onmousemove = (e) => {
  31. if (painting === true) {
  32. drawLine(last[0], last[1], e.clientX, e.clientY);
  33. last = [e.clientX, e.clientY];
  34. }
  35. };
  36. canvas.onmouseup = () => {
  37. painting = false;
  38. };
  39. }
  40. function drawLine(x1, y1, x2, y2) {
  41. ctx.beginPath();
  42. ctx.moveTo(x1, y1);
  43. ctx.lineTo(x2, y2);
  44. ctx.stroke();
  45. }