canvas 画笔、橡皮擦和文本输入

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div class="toolbar">
    <button class="pencil">pencil</button>
    <button class="eraser">eraser</button>
    <input class="inputText" type="text" placeholder="请输入文本">
    <button class="text">text</button>
    <button class="fillColor">fillCo</button>
  </div>
  <canvas class="mycanvas" width="400" height="300"></canvas>
  <script>
    const canvas = document.querySelector('.mycanvas')
    const ctx = canvas.getContext('2d')
    const canvasBackgroundColor = '#aaa'
    ctx.fillStyle = canvasBackgroundColor
    ctx.fillRect(0,0,400,300)

    const pencil = document.querySelector('.pencil')
    pencil.addEventListener('click', pencilTool, false)

    const eraser = document.querySelector('.eraser')
    eraser.addEventListener('click', eraserTool, false)

    const textBtn = document.querySelector('.text')
    textBtn.addEventListener('click', textTool, false)

    const fillCoBtn = document.querySelector('.fillColor')
    fillCoBtn.addEventListener('click', fillColorTool, false)

    function draw(strokeStyle){
      canvas.onmousedown = (e) => {
        const x1 = e.clientX - canvas.offsetLeft
        const y1 = e.clientY - canvas.ofsfsetTop
        ctx.lineWidth = 1
        ctx.beginPath()
        ctx.moveTo(x1, y1)
        canvas.onmousemove = (e) => {
          const x2 = e.clientX - canvas.offsetLeft
          const y2 = e.clientY - canvas.offsetTop
          ctx.lineTo(x2, y2)
          ctx.strokeStyle = strokeStyle
          ctx.stroke()
        }
        canvas.onmouseup = () => {
          ctx.closePath()
          canvas.onmousemove = canvas.onmouseup = null
        }
      } 
    }

    function pencilTool(){
      let strokeStyle = '#fff'
      draw(strokeStyle)
    }

    function eraserTool(){
      let strokeStyle = canvasBackgroundColor
      draw(strokeStyle)
    }

    function getInputText(){
      return document.querySelector('.inputText').value
    }
    function textTool(){
      // 清除鼠标事件
      canvas.onmousedown = null
      const inputText = getInputText()
      canvas.onmouseup = (e) => {
        const x = e.clientX - canvas.offsetLeft
        const y = e.clientY - canvas.offsetTop
        ctx.font = "10px serif"
        ctx.fillStyle = '#000'
        if (inputText){
          ctx.fillText(inputText, x, y)
        } else {
          alert('请输入文本')
        }
      }
    }

    function fillColorTool(){
      canvas.onmouseup = (e) => {
        console.log('fillColor')
      }
    }
  </script>
</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值