Canvas(九) 使用Canvas交互和isPointInPath

clearRect(清除以前写的 Rect)

context.clearRect(x,y,width,height)

window.onload = function () {
  var canvas = document.getElementById('canvas')
  canvas.width = 800
  canvas.height = 800
  var context = canvas.getContext('2d')
  //清除
  context.clearRect(100, 100, canvas.width, canvas.height)
  context.fillStyle = '#ff0000' //必须要重新指定
  //清除结束
}

isPointInPath 判断点是否在绘制的图形内

window.onload = function () {
  var canvas = document.getElementById('canvas')
  canvas.width = 800
  canvas.height = 800
  var context = canvas.getContext('2d')
  context.rect(10, 10, 100, 100) //路径
  context.stroke()
  context.addEventListener('click', function (e) {
    var x = e.pageX - canvas.offsetLeft
    var y = e.pageY - canvas.offsetTop
    alert(context.isPointInPath(x, y)) //应该是true
  })
}

文章作者: 雾烟云
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 雾烟云 !
  目录