canvas实现鼠标滚轮滚动缩放画布

2023-12-14 04:55:40
const canvas = document.createElement('canvas')
canvas.width = 400
canvas.height = 400
canvas.className = 'main_canvas'
document.body.appendChild(canvas)
const ctx = canvas.getContext('2d')

const info = {
  offset: {x: 0, y: 0},
  scale: 1,
  scaleStep: 0.1,
  minScale: 0.5,
  maxScale: 2
}

// 获取鼠标在canvas画布上的坐标
const getCanvasPostion = (e) => {
  return {
    x: e.offsetX,
    y: e.offsetY,
  }
}

//计算呢两点之间的距离
const getDistance = (p1, p2) => {
  return Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)
}

//更新画布
const updateCanvas = () => {
  const backgroundImage = new Image() // 创建Image对象
  backgroundImage.src = 'https://ts1.cn.mm.bing.net/th/id/R-C.66d7b796377883a92aad65b283ef1f84?rik=sQ%2fKoYAcr%2bOwsw&riu=http%3a%2f%2fwww.quazero.com%2fuploads%2fallimg%2f140305%2f1-140305131415.jpg&ehk=Hxl%2fQ9pbEiuuybrGWTEPJOhvrFK9C3vyCcWicooXfNE%3d&risl=&pid=ImgRaw&r=0' //设置图片路径
  backgroundImage.onload = function(){
    console.log('图片加载完成');
    ctx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height)  //绘制背景图片
  }
}

updateCanvas()

//监听滚轮滚动缩放画布
canvas.addEventListener('wheel', (e) => {
  e.preventDefault()
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  const canvasPosition = getCanvasPostion(e)  //获取画布上的事件坐标
  console.log(canvasPosition)
  const realCanvasPosition = { //鼠标在画布上的坐标
    x: canvasPosition.x - info.offset.x,
    y: canvasPosition.y - info.offset.y
  }
  // 放缩时产生的偏移量
  const deltaX = realCanvasPosition.x / info.scale * info.scaleStep
  const deltaY = realCanvasPosition.y / info.scale * info.scaleStep
  if (e.wheelDelta > 0 && info.scale < info.maxScale) {
    console.log('上滚');
    info.offset.x  -= deltaX
    info.offset.y  -= deltaY
    info.scale += info.scaleStep
  }else if (e.wheelDelta <= 0 && info.scale > info.minScale){
    console.log('下滚');
    info.offset.x  += deltaX
    info.offset.y  += deltaY
    info.scale -= info.scaleStep
  }
  ctx.setTransform(info.scale, 0, 0, info.scale, info.offset.x, info.offset.y)
  updateCanvas()
})

canvas实现鼠标滚轮滚动缩放画布效果

文章来源:https://blog.csdn.net/qq_45290368/article/details/134869641
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。