Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
873 views
in Technique[技术] by (71.8m points)

canvas 鼠标移动绘制 如何保存上一个矩形

 mousedown(e) {
      const canvasMap = document.getElementById('canvasMap')
      var ctx = canvasMap.getContext('2d')
      ctx.save()    // 保存之前的原始环境
      this.flag = true
      this.x = e.offsetX // 鼠标落下时的X
      this.y = e.offsetY // 鼠标落下时的Y
    },
    mouseup(e) {
      const canvasMap = document.getElementById('canvasMap')
      var ctx = canvasMap.getContext('2d')
      ctx.restore()    // 保存之前的原始环境

      this.flag = false
    },
    mousemove(e) {
      this.drawRect(e)
    },
    drawRect(e) {
      if (this.flag) {
        const canvasMap = document.getElementById('canvasMap')

        var ctx = canvasMap.getContext('2d')
        const x = this.x
        const y = this.y

        ctx.clearRect(0, 0, canvasMap.width, canvasMap.height)
        ctx.beginPath()

        // 设置线条颜色,必须放在绘制之前
        ctx.strokeStyle = '#00ff00'
        // 线宽设置,必须放在绘制之前
        ctx.lineWidth = 1

        ctx.strokeRect(x, y, e.offsetX - x, e.offsetY - y)
      }
    }

在鼠标移动的时候调用clearRect 清除了移动过程中绘制的矩形
但是这样每次绘制第二个矩形的时候都会清除了上一个矩形


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
saveData() {
      const canvasMap = document.getElementById('canvasMap')
      var ctx = canvasMap.getContext('2d')
      this.drawingSurfaceImageData = ctx.getImageData(0, 0, 800, 500)
    },
    restoreData() {
      const canvasMap = document.getElementById('canvasMap')
      var ctx = canvasMap.getContext('2d')
      ctx.putImageData(this.drawingSurfaceImageData, 0, 0)
    },
    mousedown(e) {
      this.flag = true
      this.x = e.offsetX // 鼠标落下时的X
      this.y = e.offsetY // 鼠标落下时的Y
      this.saveData()
    },
    mouseup() {
      this.flag = false
    },
    mousemove(e) {
      if (this.flag) {
        this.restoreData()
        this.drawRect(e)
      }
    },
    drawRect(e) {
      const canvasMap = document.getElementById('canvasMap')
      var ctx = canvasMap.getContext('2d')
      const x = this.x
      const y = this.y
      ctx.save()
      ctx.beginPath()
      ctx.strokeStyle = '#00ff00'
      ctx.lineWidth = 1
      ctx.strokeRect(x, y, e.offsetX - x, e.offsetY - y)
      ctx.restore()
    }
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...