Canvas.vue?8931:151 Uncaught TypeError: Cannot read properties of undefined (reading 'lineTo')
Задача стоит написать real-time drawing board. Использую сокет для связи, и канвас для рисования. При рисовании с сервера приходят координаты их нужно вывести у других пользователей.
внутри скрипта эти методы:
mounted () {
this.canvas = this.$refs.canvas
this.context = this.canvas.getContext('2d')
this.canvas.addEventListener('mousedown', this.mousedown)
this.canvas.addEventListener('mousemove', this.mousemove)
this.canvas.addEventListener('mouseup', this.mouseup)
this.onSocketAnswer()
},
methods: {
mousedown (e) {
const rect = this.canvas.getBoundingClientRect()
const x = e.clentX - rect.left
const y = e.clentY - rect.top
this.isDrawing = true
this.startX = x
this.startY = y
},
mousemove (e) {
const rect = this.canvas.getBoundingClientRect()
const x = e.clientX - rect.left
const y = e.clientY - rect.top
if (this.isDrawing) {
this.context.beginPath()
this.context.moveTo(this.startX, this.startY)
console.log('XX', x)
console.log('YY', y)
this.context.lineTo(x, y)
this.context.lineWidth = this.currentWidth
// this.context.globalCompositeOperation = 'source-over'
this.context.lineCap = 'round'
this.context.strokeStyle = this.colorArray[this.currentColor]
this.context.stroke()
this.startX = x
this.startY = y
this.points.push({
x: x,
y: y
})
}
},
mouseup (e) {
this.isDrawing = false
this.pathsry.push(this.points)
// if (this.points.length > 0) {
// localStorage.points = JSON.stringify(this.points)
// }
console.log('>>>', this.points)
this.socket.emit('draw', this.points)
this.points = []
console.log('>>>POINTS0', this.points)
console.log('>>>pathsry', this.pathsry)
},
eraseCanvas (index) {
this.context.globalCompositeOperation = 'destination-out'
this.currentColor = index
this.context.strokeStyle = this.colorArray[this.currentColor]
},
resetCanvas () {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height)
this.pathsry = []
},
undoCanvas () {
this.pathsry.splice(-1, 1)
},
openChooseColor () {
this.isOpenColor = !this.isOpenColor
},
openChooseWidth () {
this.isOpenWidth = !this.isOpenWidth
},
chooseColor (index) {
this.currentColor = index
},
chooseWidth (index) {
this.currentWidth = index
},
onSocketAnswer: function () {
this.socket.on('data', function (data) {
console.log('came smthg', data)
data.map(el => {
console.log('el.x', el.x)
console.log('el.y', el.y)
this.context.lineTo(el.x, el.y)
this.context.stroke()
})
})
}
}
Внутри функции onSocketAnswer до строки this.context.lineTo(el.x, el.y) все нормально получает, выводит, но на первом же цикле выдает ошибку:
Canvas.vue?8931:151 Uncaught TypeError: Cannot read properties of undefined (reading 'lineTo')
хотя там все значения el не пустые. Не могу понять почему приходит эта ошибка