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

javascript 复制代码
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实现鼠标滚轮滚动缩放画布效果

相关推荐
GreenTea7 分钟前
GrokBot 核心成员 Lauren Tan:每月交付 2000 个 PR 的人,是怎么用 AI 的
前端·后端·架构
mCell1 小时前
用 Knip 清理 AI Coding 留下的冗余代码
前端·ai编程·前端工程化
笃行3502 小时前
使用Rokid AIUI做了一个童年推箱子游戏
前端
excel3 小时前
前端加密的作用与使用场景
前端
计算机魔术师4 小时前
纽约时报版权诉讼披露:微软高管内部称训练 AI 是人类历史上最大规模劳动窃取
前端
去伪存真5 小时前
大模型的参数量为什么那么大?
前端·人工智能
IT_陈寒5 小时前
Java空指针这次真把我坑惨了
前端·人工智能·后端
高级程序源6 小时前
django大学生创新创业项目管理系统94923-计算机课程设计、毕业设计
javascript·vue.js·spring boot·后端·python·django·课程设计
八荒启·交互动画6 小时前
# Web特效020—让 Web 特效真正动起来:时间循环应该怎么接
前端·webgl·网页特效·八荒启-交互动画·八荒启
动恰客流统计6 小时前
线下零售数字化浪潮下,客流统计的3个核心发展趋势
大数据·前端·人工智能