如何在Canvas中添加事件的方法示例

2020-04-24 19:27:36易采站长站整理


const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')

ctx.beginPath()
ctx.moveTo(10, 10)
ctx.lineTo(10, 50)
ctx.lineTo(50, 50)
ctx.lineTo(50, 10)
ctx.fillStyle= 'black'
ctx.fill()
ctx.closePath()

canvas.addEventListener('click', function (e) {
const canvasInfo = canvas.getBoundingClientRect()
console.log(ctx.isPointInPath(e.clientX - canvasInfo.left, e.clientY - canvasInfo.top))
})

如图所示,灰色部分为Canvas所占据的区域,黑色为我们实际添加事件的区域,在我们点击黑色区域后,实际也的确如我们所愿,打印出来的值为true。貌似Canvas的事件监听就这么简单的解决了,不过事情真有这么简单吗。显然是不可能的!我们再来举个例子,这时候有两个区域,并且我们需要分别给其绑定不同的事件:


const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')

ctx.beginPath()
ctx.moveTo(10, 10)
ctx.lineTo(10, 50)
ctx.lineTo(50, 50)
ctx.lineTo(50, 10)
ctx.fillStyle= 'black'
ctx.fill()
ctx.closePath()

ctx.beginPath()
ctx.moveTo(100, 100)
ctx.lineTo(100, 150)
ctx.lineTo(150, 150)
ctx.lineTo(150, 100)
ctx.fillStyle= 'red'
ctx.fill()
ctx.closePath()

canvas.addEventListener('click', function (e) {
const canvasInfo = canvas.getBoundingClientRect()
console.log(ctx.isPointInPath(e.clientX - canvasInfo.left, e.clientY - canvasInfo.top))
})

这个时候,结果就不再如同我们所预计的一样,当点击其中黑色区域时,打印的值为false,点击红色区域时,打印的值为true。

其实原因很简单,因为上述代码,我们实际创建了两个Path,而isPointInPath方法实际只检测当前点是否处于最后一个Path当中,而例子中红色区域为最后一个Path,所以只有点击红色区域时,isPointInPath方法才能判断为true。现在我们改造一下代码:


const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
let drawArray = []

function draw1 () {
ctx.beginPath()
ctx.moveTo(10, 10)
ctx.lineTo(10, 50)
ctx.lineTo(50, 50)
ctx.lineTo(50, 10)
ctx.fillStyle= 'black'
ctx.fill()
}

function draw2 () {
ctx.beginPath()
ctx.moveTo(100, 100)
ctx.lineTo(100, 150)
ctx.lineTo(150, 150)
ctx.lineTo(150, 100)
ctx.fillStyle= 'red'
ctx.fill()
ctx.closePath()