canvas画图

111 阅读1分钟

canvas画图板

HTML

<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>画板</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <canvas id="canvas" width="100" height="100"></canvas>
    <script>
      let canvas = document.getElementById("canvas");  //通过ID找到canvas
      canvas.width = document.documentElement.clientWidth; //对象内容的可视区宽度,不包括滚动条等边线,会随对象显示大小的变化而改变
      canvas.height = document.documentElement.clientHeight;  //对象内容的可视区高度,不包括滚动条等边线,会随对象显示大小的变化而改变

      let ctx = canvas.getContext("2d");
      ctx.fillStyle = "black";  //填充样式
      ctx.strokeStyle = "black";  //描边样式
      ctx.lineWidth = 10;
      ctx.lineCap = "round";

      let painting = false;
      let last;

      let isTouchDevice = "ontouchstart" in document.documentElement;
      if (isTouchDevice) {
        canvas.ontouchstart = (e) => {
          let x = e.touches[0].clientX;
          let y = e.touches[0].clientY;
          last = [x, y];
        };
        canvas.ontouchmove = (e) => {
          let x = e.touches[0].clientX;
          let y = e.touches[0].clientY;
          drawLine(last[0], last[1], x, y);
          last = [x, y];
        };
      } else {
        canvas.onmousedown = (e) => {
          painting = true;
          last = [e.clientX, e.clientY];
          console.log(last);
        };

        canvas.onmousemove = (e) => {
          if (painting === true) {
            drawLine(last[0], last[1], e.clientX, e.clientY);
            last = [e.clientX, e.clientY];
          }
        };

        canvas.onmouseup = () => {
          painting = false;
        };
      }
      function drawLine(x1, y1, x2, y2) {
        ctx.beginPath();
        ctx.moveTo(x1, y1);
        ctx.lineTo(x2, y2);
        ctx.stroke();
      }
    </script>
  </body>
</html>

CSS

*{  margin: 0;padding: 0;box-sizing: border-box;}
#canvas{display: block;}
body {overflow: hidden;}

注意

canvas宽高是提前设置好的,强行在CSS里改变其宽高,直接拉升,必须就写好宽高。