Canvas鼠标画线

鼠标按下开始画线,鼠标移动根据鼠标的轨迹去画,鼠标抬起停止画线
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Canvas Drawing</title>
  <style>
    canvas {
      border: 1px solid #000;
    }
  </style>
</head>

<body>
  <canvas id="myCanvas" width="500" height="500"></canvas>

  <script>
    document.addEventListener('DOMContentLoaded', function () {
      const canvas = document.getElementById('myCanvas')
      const ctx = canvas.getContext('2d')
      let isDrawing = false

      function startDrawing (e) {
        isDrawing = true
        draw(e)
      }

      function stopDrawing () {
        isDrawing = false
        ctx.beginPath() // Reset the path for the next draw
      }

      function draw (e) {
        if (!isDrawing) return

        ctx.lineWidth = 5
        ctx.lineCap = 'round'
        ctx.strokeStyle = '#000'

        ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop)
        ctx.stroke()
        ctx.beginPath()
        ctx.moveTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop)
      }

      canvas.addEventListener('mousedown', startDrawing)
      canvas.addEventListener('mousemove', draw)
      canvas.addEventListener('mouseup', stopDrawing)
      canvas.addEventListener('mouseout', stopDrawing)
    });
  </script>
</body>

</html>

效果图
在这里插入图片描述

和上面效果相同,只是轨迹线换成了直线(鼠标移动始终显示两点直线,只能绘制有一条线)
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Canvas Drawing</title>
  <style>
    canvas {
      border: 1px solid #000;
    }
  </style>
</head>

<body>
  <canvas id="myCanvas" width="500" height="500"></canvas>

  <script>
    document.addEventListener('DOMContentLoaded', function () {
      const canvas = document.getElementById('myCanvas')
      const ctx = canvas.getContext('2d')
      let isDrawing = false
      let startX, startY

      function startDrawing (e) {
        isDrawing = true
        startX = e.clientX - canvas.offsetLeft
        startY = e.clientY - canvas.offsetTop
      }

      function drawLine (e) {
        if (!isDrawing) return

        const endX = e.clientX - canvas.offsetLeft
        const endY = e.clientY - canvas.offsetTop

        ctx.clearRect(0, 0, canvas.width, canvas.height) // Clear the canvas
        ctx.lineWidth = 5
        ctx.lineCap = 'round'
        ctx.strokeStyle = '#000'

        ctx.beginPath()
        ctx.moveTo(startX, startY)
        ctx.lineTo(endX, endY)
        ctx.stroke()
      }

      function stopDrawing () {
        isDrawing = false
      }

      canvas.addEventListener('mousedown', startDrawing)
      canvas.addEventListener('mousemove', drawLine)
      canvas.addEventListener('mouseup', stopDrawing)
      canvas.addEventListener('mouseout', stopDrawing)
    });
  </script>
</body>

</html>

效果图
在这里插入图片描述

效果图和上面相同(可以画多条直线,点击确定按钮会保留最后画的一条线)
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Canvas Drawing</title>
  <style>
    canvas {
      border: 1px solid #000;
      margin-bottom: 20px;
    }

    button {
      display: block;
      margin-top: 10px;
    }
  </style>
</head>

<body>
  <canvas id="myCanvas" width="500" height="500"></canvas>
  <button id="confirmButton">Confirm</button>

  <script>
    document.addEventListener('DOMContentLoaded', function () {
      const canvas = document.getElementById('myCanvas')
      const ctx = canvas.getContext('2d')
      let lines = [] // 画线的数组
      let lines2 = [] // 点击确定后存放的按钮
      let num = 0
      let isDrawing = false
      let startPoint = {}
      let endPoint = {}

      function startDrawing (e) {
        isDrawing = true
        startPoint = {
          x: e.clientX - canvas.offsetLeft,
          y: e.clientY - canvas.offsetTop
        }
      }

      function drawLine (e) {
        if (!isDrawing) return

        endPoint = {
          x: e.clientX - canvas.offsetLeft,
          y: e.clientY - canvas.offsetTop
        }

        ctx.clearRect(0, 0, canvas.width, canvas.height) // Clear the canvas

        ctx.lineWidth = 5
        ctx.lineCap = 'round'
        ctx.strokeStyle = '#000'

        lines.forEach(line => {
          ctx.beginPath()
          ctx.moveTo(line.start.x, line.start.y)
          ctx.lineTo(line.end.x, line.end.y)
          ctx.stroke()
        })

        ctx.beginPath()
        ctx.moveTo(startPoint.x, startPoint.y)
        ctx.lineTo(endPoint.x, endPoint.y)
        ctx.stroke()
      }

      function stopDrawing () {
        if (isDrawing) {
          isDrawing = false
          lines.push({ start: { ...startPoint }, end: { ...endPoint } })
        }
      }

      function confirmLines () {
        lines2.push(lines[lines.length - 1])
        lines = [...lines2]
        ctx.clearRect(0, 0, canvas.width, canvas.height) // Clear the canvas
        if (lines2.length > 0) {
          lines2.forEach((item) => {
            const lastLine = item
            ctx.beginPath()
            ctx.moveTo(lastLine.start.x, lastLine.start.y)
            ctx.lineTo(lastLine.end.x, lastLine.end.y)
            ctx.stroke()
          })
        }
      }

      canvas.addEventListener('mousedown', startDrawing)
      canvas.addEventListener('mousemove', drawLine)
      canvas.addEventListener('mouseup', stopDrawing)
      canvas.addEventListener('mouseout', stopDrawing)

      const confirmButton = document.getElementById('confirmButton')
      confirmButton.addEventListener('click', confirmLines)
    });
  </script>
</body>

</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以通过以下步骤来实现在 Canvas 上点击画线并可以移动和缩放的功能: 1. 定义一个数组用于保存所有画的线段,比如 `lines`; 2. 给 Canvas 添加 `mousedown` 事件监听器,当用户点击鼠标时,记录下鼠标的起始位置,并画一条从起始位置到起始位置的线段(这样可以让用户看到正在画线的过程); 3. 给 Canvas 添加 `mousemove` 事件监听器,当用户拖动鼠标时,根据当前位置和起始位置画一条线段,同时清除 Canvas 上的所有线段并重新画出 `lines` 数组中保存的所有线段; 4. 给 Canvas 添加 `mouseup` 事件监听器,当用户松开鼠标时,将当前画的线段保存到 `lines` 数组中,并将起始位置和当前位置都重置为 `(0, 0)`; 5. 给 Canvas 添加 `wheel` 事件监听器,当用户滚动鼠标滚轮时,根据滚动的方向缩放 Canvas。 下面是一个示例代码: ```javascript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const lines = []; let startX = 0, startY = 0, currX = 0, currY = 0; // 画一条直线 function drawLine(x1, y1, x2, y2) { ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); } // 清除 Canvas 并重新绘制所有线段 function redrawLines() { ctx.clearRect(0, 0, canvas.width, canvas.height); lines.forEach(line => drawLine(line[0], line[1], line[2], line[3])); } // 给 Canvas 添加鼠标事件监听器 canvas.addEventListener('mousedown', (e) => { startX = e.clientX - canvas.offsetLeft; startY = e.clientY - canvas.offsetTop; currX = startX; currY = startY; drawLine(startX, startY, currX, currY); }); canvas.addEventListener('mousemove', (e) => { if (startX === 0 && startY === 0) { return; } const x = e.clientX - canvas.offsetLeft; const y = e.clientY - canvas.offsetTop; currX = x; currY = y; redrawLines(); drawLine(startX, startY, currX, currY); }); canvas.addEventListener('mouseup', () => { lines.push([startX, startY, currX, currY]); startX = 0; startY = 0; currX = 0; currY = 0; }); canvas.addEventListener('wheel', (e) => { const delta = Math.sign(e.deltaY); const scaleFactor = delta > 0 ? 1.1 : 0.9; ctx.scale(scaleFactor, scaleFactor); redrawLines(); }); ``` 在这个示例中,我们定义了一个 `lines` 数组来保存所有画的线段;在 `mousedown` 事件监听器中记录下鼠标的起始位置并画出一条从起始位置到起始位置的线段;在 `mousemove` 事件监听器中根据当前位置和起始位置画一条线段,并清除 Canvas 并重新绘制所有线段;在 `mouseup` 事件监听器中将当前画的线段保存到 `lines` 数组中并重置起始位置和当前位置;在 `wheel` 事件监听器中根据滚轮的方向缩放 Canvas。 这个示例还比较简单,你可以根据自己的需求进行更改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

萧寂173

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值