为什么canvas.getContext未定义

时间:2019-10-19 10:23:21

标签: javascript html canvas paint

我正在开发一个Web绘画应用程序,并且this.ctx结果不确定。我正在使用javascript和canvas进行绘制。为了工作,我还需要在其他地方定义ctx。它适用于除draw之外的所有其他功能。 this.x可以正常工作,但是即使它们在构造函数中位于同一位置,也无法定义this.ctx。

  constructor () {
    super()
    this.attachShadow({ mode: 'open' })
    this.shadowRoot.appendChild(template.content.cloneNode(true))
    this.x = 0
    this.y = 0
    this.canvas = this.shadowRoot.querySelector('#canvasDrawing')
    this.ctx = this.canvas.getContext('2d')
  }

  connectedCallback () {
    this.initialize()
    this.closeWindow()
  }

  draw (e) {
    if (e.buttons !== 1) return // if mouse is pressed.....
    console.log(this.ctx)
    this.ctx.beginPath() // begin the drawing path
    this.ctx.lineWidth = 20 // width of line
    this.ctx.lineCap = 'round' // rounded end cap
    this.ctx.strokeStyle = 'red' // hex color of line
    this.ctx.moveTo(this.x, this.y) // from position
    this.setPosition(e)
    this.ctx.lineTo(this.x, this.y) // to position
    this.ctx.stroke() // draw it!
  }

  closeWindow () {
    const close = this.shadowRoot.querySelector('#board')
    close.addEventListener('click', event => {
      if (event.target === this.shadowRoot.querySelector('#close')) {
        close.classList.add('removed')
      }
    })
  }

  initialize () {
    // last known position
    this.resize()
    document.addEventListener('mousemove', this.draw)
    document.addEventListener('mousedown', this.setPosition)
    document.addEventListener('mouseenter', this.setPosition)
  }

  // resize canvas when window is resized
  resize () {
    this.ctx.canvas.width = 300
    this.ctx.canvas.height = 300
  }

  // new position from mouse events
  setPosition (e) {
    this.x = e.clientX
    this.y = e.clientY
  }

0 个答案:

没有答案