欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

程序员文章站 2022-09-11 10:00:29
这篇文章主要介绍了Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式),本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需... 20-03-18...

哈哈哈俺又来啦,这次带来的是canvas实现一些画布功能的文章,希望大家喜欢!

Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

前言

因为也是大三了,最近俺也在找实习,之前有一个自己的小项目:

https://github.com/zhcxk1998/school-partners

面试官说可以往深层次思考一下,或许加一些新的功能来增加项目的难度,他提了几个建议,其中一个就是 试卷在线批阅,老师可以在上面对作业进行批注,圈圈点点等 俺当天晚上就开始研究这个东东哈哈哈,终于被我研究出来啦!

采用的是 canvas 绘制画笔,由css3的 transform 属性来进行平移与缩放,之后再详细介绍介绍

(希望大家可以留下宝贵的赞与star嘻嘻)

效果预览

Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

动图是放cdn的,如果访问不了,可以登录在线尝试尝试:

公式推导 如果不想看公式如何推导,可以直接跳过看后面的具体实现~ 1. 坐标转换公式 转换公式介绍

其实一开始也是想在网上找一下有没有相关的资料,但是可惜找不到,所以就自己慢慢的推出来了。我就举一下横坐标的例子吧!

通用公式

这个公式是表示,通过公式来将鼠标按下的坐标转换为画布中的相对坐标,这一点尤为重要

(transformorigin - downx) / scale * (scale-1) + downx - translatex = pointx

参数解释

transformorigin: transform变化的基点(通过这个属性来控制元素以哪里进行变化)
downx: 鼠标按下的坐标(注意,用的时候需要减去容器左偏移距离,因为我们要的是相对于容器的坐标)
scale: 缩放倍数,默认为1
translatex: 平移的距离

推导过程

这个公式的话,其实就比较通用,可以用在别的利用到 transform 属性的场景,至于怎么推导的话,我是用的笨办法

具体的测试代码,放在文末,需要自取~

1. 先做出两个相同的元素,然后标记上坐标,并且设置容器属性 overflow:hidden 来隐藏溢出内容

Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

ok,现在就有两个一样的矩阵啦,我们为他标记上一些红点,然后我们对左边的进行css3的样式变化 transform

矩形的宽高是 360px * 360px 的,我们定义一下他的变化属性,变化基点选择正中心,放大3倍

// css
transform-origin: 180px 180px;
transform: scale(3, 3);

得到如下结果

Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

ok,我们现在对比一下上面的结果,就会发现,放大3倍的时候,恰好是中间黑色方块占据了全部宽度。接下来我们就可以对这些点与原先没有进行变化(右边)的矩形进行对比就可以得到他们坐标的关系啦

2. 开始对两个坐标进行对比,然后推出公式

现在举一个简单的例子吧,例如我们算一下左上角的坐标(现在已经标记为黄色了)

Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

其实我们其实就可以直接心算出来坐标的关系啦

这里左边计算坐标的值是我们鼠标按下的坐标

这里左边计算坐标的值是我们鼠标按下的坐标

这里左边计算坐标的值是我们鼠标按下的坐标

  • 因为宽高是 360px ,所以分成3等份,每份宽度是 120px
  • 因为变化之后容器的宽高是不变的,变化的只有矩形本身
  • 我们可以得出左边的黄色标记坐标是 x:120 y:0 ,右边的黄色标记为 x:160 y:120 (这个其实肉眼看应该就能看出来了,实在不行可以用纸笔算一算)

这个坐标可能有点特殊,我们再换几个来计算计算(根据特殊推一般)

Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

蓝色标记:左边: x:120 y:120 ,右边: x: 160 y:160 绿色标记:左边: x: 240 y:240 ,右边: x: 200: y:200

好了,我们差不多已经可以拿到坐标之间的关系了,我们可以列一个表

Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

还觉得不放心?我们可以换一下,缩放倍数与容器宽高等进行计算

Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

不知道大家有没有感觉呢,然后我们就可以慢慢根据坐标推出通用的公式啦

(transformorigin - downx) / scale * (scale-1) + down - translatex = point

当然,我们或许还有这个 translatex 没有尝试,这个就比较简单一点了,脑内模拟一下,就知道我们可以减去位移的距离就ok啦。我们测试一下

我们先修改一下样式,新增一下位移的距离

transform-origin: 180px 180px;
transform: scale(3, 3) translate(-40px,-40px);

Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

还是我们上面的状态,ok,我们现在蓝色跟绿色的标记还是一一对应的,那我们看看现在的坐标情况

  • 蓝色:左边: x:0 y:0 ,右边: x:160 y:160
  • 绿色:左边: x:120 y:120 ,右边: x:200 y:200

我们分别运用公式算一下出来的坐标是怎么样的 (以下为经过坐标换算)

蓝色:左边: x:120 y:120 ,右边: x:160 y:160 绿色:左边: x:160 y:160 ,右边: x:200 y:200

不难发现,我们其实就相差了与位移距离 translatex/translatey 的差值,所以,我们只需要减去位移的距离就可以完美的进行坐标转换啦

测试公式

根据上面的公式,我们可以简单测试一下!这个公式到底能不能生效!!!

我们直接沿用上面的demo,测试一下如果元素进行了变化,我们鼠标点下的地方生成一个标记,位置是否显示正确。看起来很ok啊(手动滑稽)

const wrap = document.getelementbyid('wrap')
wrap.onmousedown = function (e) {
  const downx = e.pagex - wrap.offsetleft
  const downy = e.pagey - wrap.offsettop

  const scale = 3
  const translatex = -40
  const translatey = -40
  const transformoriginx = 180
  const transformoriginy = 180

  const dot = document.getelementbyid('dot')
  dot.style.left = (transformoriginx - downx) / scale * (scale - 1) + downx - translatex + 'px'
  dot.style.top = (transformoriginy - downy) / scale * (scale - 1) + downy - translatey + 'px'
}

Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

可能有人会问,为什么要减去这个 offsetleftoffsettop 呢,因为我们上面反复强调,我们计算的是鼠标点击的坐标,而这个坐标还是相对于我们展示容器的坐标,所以我们要减去容器本身的偏移量才行。

组件设计

既然demo啥的都已经测试了ok了,我们接下来就逐一分析一下这个组件应该咋设计好呢(目前仍为低配版,之后再进行优化完善)

1. 基本的画布构成

Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

我们先简单分析一下这个构成吧,其实主要就是一个画布的容器,右边一个工具栏,仅此而已

Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

大体就这样子啦!

<div classname="mark-paper__wrap" ref={wrapref}>
  <canvas
    ref={canvasref}
    classname="mark-paper__canvas">
    <p>很可惜,这个东东与您的电脑不搭!</p>
  </canvas>
  <div classname="mark-paper__sider" />
</div>

我们唯一需要的一点就是,容器需要设置属性 overflow: hidden 用来隐藏内部canvas画布溢出的内容,也就是说,我们要控制我们可视的区域。同时我们需要动态获取容器宽高来为canvas设置尺寸

2. 初始化canvas画布与填充图片

我们可以弄个方法来初始化并且填充画布,以下截取主要部分,其实就是为canvas画布设置尺寸与填充我们的图片

const fillimage = async () => {
  // 此处省略...
  
  const img: htmlimageelement = new image()

  img.src = await geturlbase64(fillimagesrc)
  img.onload = () => {
    canvas.width = img.width
    canvas.height = img.height
    context.drawimage(img, 0, 0)

    // 设置变化基点,为画布容器*
    canvas.style.transformorigin = `${wrap?.offsetwidth / 2}px ${wrap?.offsetheight / 2}px`
    // 清除上一次变化的效果
    canvas.style.transform = ''
  }
}

3. 监听canvas画布的各种鼠标事件

这个控制移动的话,我们首先可以弄一个方法来监听画布鼠标的各种事件,可以区分不同的模式来进行不同的事件处理

const handlecanvas = () => {
  const { current: canvas } = canvasref
  const { current: wrap } = wrapref
  const context: canvasrenderingcontext2d | undefined | null = canvas?.getcontext('2d')
  if (!context || !wrap) return

  // 清除上一次设置的监听,以防获取参数错误
  wrap.onmousedown = null
  wrap.onmousedown = function (event: mouseevent) {
    const downx: number = event.pagex
    const downy: number = event.pagey

    // 区分我们现在选择的鼠标模式:移动、画笔、橡皮擦
    switch (mousemode) {
      case move_mode:
        handlemovemode(downx, downy)
        break
      case line_mode:
        handlelinemode(downx, downy)
        break
      case eraser_mode:
        handleerasermode(downx, downy)
        break
      default:
        break
    }
  }

4. 实现画布移动

这个就比较好办啦,我们只需要利用鼠标按下的坐标,和我们拖动的距离就可以实现画布的移动啦,因为涉及到每次移动都需要计算最新的位移距离,我们可以定义几个变量来进行计算。

这里监听的是容器的鼠标事件,而不是canvas画布的事件,因为这样子我们可以再移动超过边界的时候也可以进行移动操作

Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

简单的总结一下:

  • 传入鼠标按下的坐标
  • 计算当前位移距离,并更新css变化效果
  • 鼠标抬起时更新最新的位移状态
// 定义一些变量,来保存当前/最新的移动状态
// 当前位移的距离
const translatepointxref: mutablerefobject<number> = useref(0)
const translatepointyref: mutablerefobject<number> = useref(0)
// 上一次位移结束的位移距离
const fillstartpointxref: mutablerefobject<number> = useref(0)
const fillstartpointyref: mutablerefobject<number> = useref(0)

// 移动时候的监听函数
const handlemovemode = (downx: number, downy: number) => {
  const { current: canvas } = canvasref
  const { current: wrap } = wrapref
  const { current: fillstartpointx } = fillstartpointxref
  const { current: fillstartpointy } = fillstartpointyref
  if (!canvas || !wrap || mousemode !== 0) return

  // 为容器添加移动事件,可以在空白处移动图片
  wrap.onmousemove = (event: mouseevent) => {
    const movex: number = event.pagex
    const movey: number = event.pagey

    // 更新现在的位移距离,值为:上一次位移结束的坐标+移动的距离
    translatepointxref.current = fillstartpointx + (movex - downx)
    translatepointyref.current = fillstartpointy + (movey - downy)

    // 更新画布的css变化
    canvas.style.transform = `scale(${canvasscale},${canvasscale}) translate(${translatepointxref.current}px,${translatepointyref.current}px)`
  }
  
  wrap.onmouseup = (event: mouseevent) => {
    const upx: number = event.pagex
    const upy: number = event.pagey
    
    // 取消事件监听
    wrap.onmousemove = null
    wrap.onmouseup = null;

    // 鼠标抬起时候,更新“上一次唯一结束的坐标”
    fillstartpointxref.current = fillstartpointx + (upx - downx)
    fillstartpointyref.current = fillstartpointy + (upy - downy)
  }
}

5. 实现画布缩放

画布缩放我主要通过右侧的滑动条以及鼠标滚轮来实现,首先我们再监听画布鼠标事件的函数中加一下监听滚轮的事件

总结一下:

  • 监听鼠标滚轮的变化
  • 更新缩放倍数,并改变样式
// 监听鼠标滚轮,更新画布缩放倍数
const handlecanvas = () => {
  const { current: wrap } = wrapref

  // 省略一万字...

  wrap.onwheel = null
  wrap.onwheel = (e: mousewheelevent) => {
    const { deltay } = e
    // 这里要注意一下,我是0.1来递增递减,但是因为js使用ieee 754,来计算,所以精度有问题,我们自己处理一下
    const newscale: number = deltay > 0
      ? (canvasscale * 10 - 0.1 * 10) / 10
      : (canvasscale * 10 + 0.1 * 10) / 10
    if (newscale < 0.1 || newscale > 2) return
    setcanvasscale(newscale)
  }
}

// 监听滑动条来控制缩放
<slider
  min={0.1}
  max={2.01}
  step={0.1}
  value={canvasscale}
  tipformatter={(value) => `${(value).tofixed(2)}x`}
  onchange={handlescalechange} />
  
const handlescalechange = (value: number) => {
  setcanvasscale(value)
}

接着我们使用hooks的副作用函数,依赖于画布缩放倍数来进行样式的更新

//监听缩放画布
useeffect(() => {
  const { current: canvas } = canvasref
  const { current: translatepointx } = translatepointxref
  const { current: translatepointy } = translatepointyref
  canvas && (canvas.style.transform = `scale(${canvasscale},${canvasscale}) translate(${translatepointx}px,${translatepointy}px)`)
}, [canvasscale])

6. 实现画笔绘制

这个就需要用到我们之前推导出来的公式啦!因为呢,仔细想一下,如果我们缩放位移之后,我们鼠标按下的位置,他的坐标可能就相对于画布来说会有变化, 所以我们需要转换一下才能进行鼠标按下的位置与画布的位置一一对应的效果

稍微总结一下:

  • 传入鼠标按下的坐标
  • 通过公式转换,开始在对应坐标下绘制
  • 鼠标抬起时,取消事件监听
// 利用公式转换一下坐标
const generatelinepoint = (x: number, y: number) => {
  const { current: wrap } = wrapref
  const { current: translatepointx } = translatepointxref
  const { current: translatepointy } = translatepointyref
  const wrapwidth: number = wrap?.offsetwidth || 0
  const wrapheight: number = wrap?.offsetheight || 0
  // 缩放位移坐标变化规律
  // (transformorigin - downx) / scale * (scale-1) + downx - translatex = pointx
  const pointx: number = ((wrapwidth / 2) - x) / canvasscale * (canvasscale - 1) + x - translatepointx
  const pointy: number = ((wrapheight / 2) - y) / canvasscale * (canvasscale - 1) + y - translatepointy

  return {
    pointx,
    pointy
  }
}

// 监听鼠标画笔事件
const handlelinemode = (downx: number, downy: number) => {
  const { current: canvas } = canvasref
  const { current: wrap } = wrapref
  const context: canvasrenderingcontext2d | undefined | null = canvas?.getcontext('2d')
  if (!canvas || !wrap || !context) return

  const offsetleft: number = canvas.offsetleft
  const offsettop: number = canvas.offsettop
  // 减去画布偏移的距离(以画布为基准进行计算坐标)
  downx = downx - offsetleft
  downy = downy - offsettop

  const { pointx, pointy } = generatelinepoint(downx, downy)
  context.globalcompositeoperation = "source-over"
  context.beginpath()
  // 设置画笔起点
  context.moveto(pointx, pointy)

  canvas.onmousemove = null
  canvas.onmousemove = (event: mouseevent) => {
    const movex: number = event.pagex - offsetleft
    const movey: number = event.pagey - offsettop
    const { pointx, pointy } = generatelinepoint(movex, movey)
    // 开始绘制画笔线条~
    context.lineto(pointx, pointy)
    context.stroke()
  }
  canvas.onmouseup = () => {
    context.closepath()
    canvas.onmousemove = null
    canvas.onmouseup = null
  }
}

7. 橡皮擦的实现

橡皮擦目前还有点问题,现在的话是通过将 canvas 画布的背景图片 + globalcompositeoperation 这个属性来模拟橡皮擦的实现,不过,这时候图片生成出来之后,橡皮擦的痕迹会变成白色,而不是透明

此步骤与画笔实现差不多,只有一点点小变动

设置属性 context.globalcompositeoperation = "destination-out"

// 目前橡皮擦还有点问题,前端显示正常,保存图片下来,擦除的痕迹会变成白色
const handleerasermode = (downx: number, downy: number) => {
  const { current: canvas } = canvasref
  const { current: wrap } = wrapref
  const context: canvasrenderingcontext2d | undefined | null = canvas?.getcontext('2d')
  if (!canvas || !wrap || !context) return

  const offsetleft: number = canvas.offsetleft
  const offsettop: number = canvas.offsettop
  downx = downx - offsetleft
  downy = downy - offsettop

  const { pointx, pointy } = generatelinepoint(downx, downy)

  context.beginpath()
  context.moveto(pointx, pointy)

  canvas.onmousemove = null
  canvas.onmousemove = (event: mouseevent) => {
    const movex: number = event.pagex - offsetleft
    const movey: number = event.pagey - offsettop
    const { pointx, pointy } = generatelinepoint(movex, movey)
    context.globalcompositeoperation = "destination-out"
    context.linewidth = linewidth
    context.lineto(pointx, pointy)
    context.stroke()
  }
  canvas.onmouseup = () => {
    context.closepath()
    canvas.onmousemove = null
    canvas.onmouseup = null
  }
}

8. 撤销与恢复的功能实现

这个的话,我们首先需要了解常见的撤销与恢复的功能的逻辑 分几种情况吧

  • 若当前状态处于第一个位置,则不允许撤销
  • 若当前状态处于最后一个位置,则不允许恢复
  • 如果当前撤销了,然而更新了状态,则取当前状态为最新的状态(也就是说不允许恢复了,这个刚更新的状态就是最新的)

画布状态的更新

所以我们需要设置一些变量来存,状态列表,与当前画笔的状态下标

// 定义参数存东东
const canvashistroylistref: mutablerefobject<imagedata[]> = useref([])
const [canvascurrenthistory, setcanvascurrenthistory] = usestate<number>(0)

我们还需要在初始化canvas的时候,我们就添加入当前的状态存入列表中,作为最先开始的空画布状态

const fillimage = async () => {
  // 省略一万字...

  img.src = await geturlbase64(fillimagesrc)
  img.onload = () => {
    const imagedata: imagedata = context.getimagedata(0, 0, canvas.width, canvas.height)
    canvashistroylistref.current = []
    canvashistroylistref.current.push(imagedata)
    setcanvascurrenthistory(1)
  }
}

然后我们就实现一下,画笔更新时候,我们也需要将当前的状态添加入 画笔状态列表 ,并且更新当前状态对应的下标,还需要处理一下一些细节

总结一下:

  • 鼠标抬起时,获取当前canvas画布状态
  • 添加进状态列表中,并且更新状态下标
  • 如果当前处于撤销状态,若使用画笔更新状态,则将当前的最为最新的状态,原先位置之后的状态全部清空
const handlelinemode = (downx: number, downy: number) => {
  // 省略一万字...
  canvas.onmouseup = () => {
    const imagedata: imagedata = context.getimagedata(0, 0, canvas.width, canvas.height)

    // 如果此时处于撤销状态,此时再使用画笔,则将之后的状态清空,以刚画的作为最新的画布状态
    if (canvascurrenthistory < canvashistroylistref.current.length) {
      canvashistroylistref.current = canvashistroylistref.current.slice(0, canvascurrenthistory)
    }
    canvashistroylistref.current.push(imagedata)
    setcanvascurrenthistory(canvascurrenthistory + 1)
    context.closepath()
    canvas.onmousemove = null
    canvas.onmouseup = null
  }
}

画布状态的撤销与恢复

ok,其实现在关于画布状态的更新,我们已经完成了。接下来我们需要处理一下状态的撤销与恢复的功能啦

我们先定义一下这个工具栏吧

Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

然后我们设置对应的事件,分别是撤销,恢复,与清空,其实都很容易看懂,最多就是处理一下边界情况。

const handlerollback = () => {
  const isfirsthistory: boolean = canvascurrenthistory === 1
  if (isfirsthistory) return
  setcanvascurrenthistory(canvascurrenthistory - 1)
}

const handlerollforward = () => {
  const { current: canvashistroylist } = canvashistroylistref
  const islasthistory: boolean = canvascurrenthistory === canvashistroylist.length
  if (islasthistory) return
  setcanvascurrenthistory(canvascurrenthistory + 1)
}

const handleclearcanvasclick = () => {
  const { current: canvas } = canvasref
  const context: canvasrenderingcontext2d | undefined | null = canvas?.getcontext('2d')
  if (!canvas || !context || canvascurrenthistory === 0) return

  // 清空画布历史
  canvashistroylistref.current = [canvashistroylistref.current[0]]
  setcanvascurrenthistory(1)

  message.success('画布清除成功!')
}

事件设置好之后,我们就可以开始监听一下这个 canvascurrenthistory 当前状态下标,使用副作用函数进行处理

useeffect(() => {
  const { current: canvas } = canvasref
  const { current: canvashistroylist } = canvashistroylistref
  const context: canvasrenderingcontext2d | undefined | null = canvas?.getcontext('2d')
  if (!canvas || !context || canvascurrenthistory === 0) return
  context?.putimagedata(canvashistroylist[canvascurrenthistory - 1], 0, 0)
}, [canvascurrenthistory])

为canvas画布填充图像信息!

这样就大功告成啦!!!

9. 实现鼠标图标的变化

我们简单的处理一下,画笔模式则是画笔的图标,橡皮擦模式下鼠标是橡皮擦,移动模式下就是普通的移动图标

切换模式时候,设置一下不同的图标

const handlemousemodechange = (event: radiochangeevent) => {
  const { target: { value } } = event
  const { current: canvas } = canvasref
  const { current: wrap } = wrapref

  setmousemode(value)

  if (!canvas || !wrap) return
  switch (value) {
    case move_mode:
      canvas.style.cursor = 'move'
      wrap.style.cursor = 'move'
      break
    case line_mode:
      canvas.style.cursor = `url('http://cdn.algbb.cn/pencil.ico') 6 26, pointer`
      wrap.style.cursor = 'default'
      break
    case eraser_mode:
      message.warning('橡皮擦功能尚未完善,保存图片会出现错误')
      canvas.style.cursor = `url('http://cdn.algbb.cn/eraser.ico') 6 26, pointer`
      wrap.style.cursor = 'default'
      break
    default:
      canvas.style.cursor = 'default'
      wrap.style.cursor = 'default'
      break
  }
}

10. 切换图片

现在的话只是一个demo状态,通过点击选择框,切换不同的图片

Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

// 重置变换参数,重新绘制图片
useeffect(() => {
  setisloading(true)
  translatepointxref.current = 0
  translatepointyref.current = 0
  fillstartpointxref.current = 0
  fillstartpointyref.current = 0
  setcanvasscale(1)
  fillimage()
}, [fillimagesrc])

const handlepaperchange = (value: string) => {
  const fillimagelist = {
    'xueshengjia': 'http://cdn.algbb.cn/test/canvastest.jpg',
    'xueshengyi': 'http://cdn.algbb.cn/test/canvastest2.png',
    'xueshengbing': 'http://cdn.algbb.cn/emoji/30.png',
  }
  setfillimagesrc(fillimagelist[value])
}

注意事项

注意容器的偏移量

我们需要注意一下,因为公式中的 downx 是相对容器的坐标,也就是说,我们需要减去容器的偏移量,这种情况会出现在使用了 margin 等参数,或者说上方或者左侧有别的元素的情况

我们输出一下我们红色的元素的 offsetleft 等属性,会发现他是已经本身就有50的偏移量了,我们计算鼠标点击的坐标的时候就要减去这一部分的偏移量

Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

window.onload = function () {
  const test = document.getelementbyid('test')
  console.log(`offsetleft: ${test.offsetleft}, offsetheight: ${test.offsettop}`)
}

html,
body {
  margin: 0;
  padding: 0;
}

#test {
  width: 50px;
  height: 50px;
  margin-left: 50px;
  background: red;
}

<div class="container">
  <div id="test"></div>
</div>

注意父组件使用relative相对布局的情况

假如我们现在有一种这种的布局,打印红色元素的偏移量,看起来都挺正常的

Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

但是如果我们目标元素的父元素(也就是黄色部分)设置 relative 相对布局

.wrap {
  position: relative;
  width: 400px;
  height: 300px;
  background: yellow;
}

<div class="container">
  <div class="sider"></div>
  <div class="wrap">
    <div id="test"></div>
  </div>
</div>

这时候我们打印出来的偏移量会是多少呢

Html5 Canvas实现图片标记、缩放、移动和保存历史状态功能 (附转换公式)

两次答案不一样啊,因为我们的偏移量是根据相对位置来计算的,如果父容器使用相对布局,则会影响我们子元素的偏移量

组件代码(低配版)

import react, { fc, componenttype, useeffect, useref, refobject, usestate, mutablerefobject } from 'react'
import { custombreadcrumb } from '@/admin/components'
import { routecomponentprops } from 'react-router-dom';
import { formcomponentprops } from 'antd/lib/form';
import {
  slider, radio, button, tooltip, icon, select, spin, message, popconfirm
} from 'antd';

import './index.scss'
import { radiochangeevent } from 'antd/lib/radio';
import { geturlbase64 } from '@/admin/utils/geturlbase64'

const { option, optgroup } = select;

type markpaperprops = routecomponentprops & formcomponentprops

const markpaper: fc<markpaperprops> = (props: markpaperprops) => {
  const move_mode: number = 0
  const line_mode: number = 1
  const eraser_mode: number = 2
  const canvasref: refobject<htmlcanvaselement> = useref(null)
  const containerref: refobject<htmldivelement> = useref(null)
  const wrapref: refobject<htmldivelement> = useref(null)
  const translatepointxref: mutablerefobject<number> = useref(0)
  const translatepointyref: mutablerefobject<number> = useref(0)
  const fillstartpointxref: mutablerefobject<number> = useref(0)
  const fillstartpointyref: mutablerefobject<number> = useref(0)
  const canvashistroylistref: mutablerefobject<imagedata[]> = useref([])
  const [linecolor, setlinecolor] = usestate<string>('#fa4b2a')
  const [fillimagesrc, setfillimagesrc] = usestate<string>('')
  const [mousemode, setmousemode] = usestate<number>(move_mode)
  const [linewidth, setlinewidth] = usestate<number>(5)
  const [canvasscale, setcanvasscale] = usestate<number>(1)
  const [isloading, setisloading] = usestate<boolean>(false)
  const [canvascurrenthistory, setcanvascurrenthistory] = usestate<number>(0)

  useeffect(() => {
    setfillimagesrc('http://cdn.algbb.cn/test/canvastest.jpg')
  }, [])

  // 重置变换参数,重新绘制图片
  useeffect(() => {
    setisloading(true)
    translatepointxref.current = 0
    translatepointyref.current = 0
    fillstartpointxref.current = 0
    fillstartpointyref.current = 0
    setcanvasscale(1)
    fillimage()
  }, [fillimagesrc])

  // 画布参数变动时,重新监听canvas
  useeffect(() => {
    handlecanvas()
  }, [mousemode, canvasscale, canvascurrenthistory])

  // 监听画笔颜色变化
  useeffect(() => {
    const { current: canvas } = canvasref
    const context: canvasrenderingcontext2d | undefined | null = canvas?.getcontext('2d')
    if (!context) return

    context.strokestyle = linecolor
    context.linewidth = linewidth
    context.linejoin = 'round'
    context.linecap = 'round'
  }, [linewidth, linecolor])

  //监听缩放画布
  useeffect(() => {
    const { current: canvas } = canvasref
    const { current: translatepointx } = translatepointxref
    const { current: translatepointy } = translatepointyref
    canvas && (canvas.style.transform = `scale(${canvasscale},${canvasscale}) translate(${translatepointx}px,${translatepointy}px)`)
  }, [canvasscale])

  useeffect(() => {
    const { current: canvas } = canvasref
    const { current: canvashistroylist } = canvashistroylistref
    const context: canvasrenderingcontext2d | undefined | null = canvas?.getcontext('2d')
    if (!canvas || !context || canvascurrenthistory === 0) return
    context?.putimagedata(canvashistroylist[canvascurrenthistory - 1], 0, 0)
  }, [canvascurrenthistory])

  const fillimage = async () => {
    const { current: canvas } = canvasref
    const { current: wrap } = wrapref
    const context: canvasrenderingcontext2d | undefined | null = canvas?.getcontext('2d')
    const img: htmlimageelement = new image()

    if (!canvas || !wrap || !context) return

    img.src = await geturlbase64(fillimagesrc)
    img.onload = () => {
      // 取中间渲染图片
      // const centerx: number = canvas && canvas.width / 2 - img.width / 2 || 0
      // const centery: number = canvas && canvas.height / 2 - img.height / 2 || 0
      canvas.width = img.width
      canvas.height = img.height

      // 背景设置为图片,橡皮擦的效果才能出来
      canvas.style.background = `url(${img.src})`
      context.drawimage(img, 0, 0)
      context.strokestyle = linecolor
      context.linewidth = linewidth
      context.linejoin = 'round'
      context.linecap = 'round'

      // 设置变化基点,为画布容器*
      canvas.style.transformorigin = `${wrap?.offsetwidth / 2}px ${wrap?.offsetheight / 2}px`
      // 清除上一次变化的效果
      canvas.style.transform = ''
      const imagedata: imagedata = context.getimagedata(0, 0, canvas.width, canvas.height)
      canvashistroylistref.current = []
      canvashistroylistref.current.push(imagedata)
      // canvascurrenthistoryref.current = 1
      setcanvascurrenthistory(1)
      settimeout(() => { setisloading(false) }, 500)
    }
  }

  const generatelinepoint = (x: number, y: number) => {
    const { current: wrap } = wrapref
    const { current: translatepointx } = translatepointxref
    const { current: translatepointy } = translatepointyref
    const wrapwidth: number = wrap?.offsetwidth || 0
    const wrapheight: number = wrap?.offsetheight || 0
    // 缩放位移坐标变化规律
    // (transformorigin - downx) / scale * (scale-1) + downx - translatex = pointx
    const pointx: number = ((wrapwidth / 2) - x) / canvasscale * (canvasscale - 1) + x - translatepointx
    const pointy: number = ((wrapheight / 2) - y) / canvasscale * (canvasscale - 1) + y - translatepointy

    return {
      pointx,
      pointy
    }
  }

  const handlelinemode = (downx: number, downy: number) => {
    const { current: canvas } = canvasref
    const { current: wrap } = wrapref
    const context: canvasrenderingcontext2d | undefined | null = canvas?.getcontext('2d')
    if (!canvas || !wrap || !context) return

    const offsetleft: number = canvas.offsetleft
    const offsettop: number = canvas.offsettop
    // 减去画布偏移的距离(以画布为基准进行计算坐标)
    downx = downx - offsetleft
    downy = downy - offsettop

    const { pointx, pointy } = generatelinepoint(downx, downy)
    context.globalcompositeoperation = "source-over"
    context.beginpath()
    context.moveto(pointx, pointy)

    canvas.onmousemove = null
    canvas.onmousemove = (event: mouseevent) => {
      const movex: number = event.pagex - offsetleft
      const movey: number = event.pagey - offsettop
      const { pointx, pointy } = generatelinepoint(movex, movey)
      context.lineto(pointx, pointy)
      context.stroke()
    }
    canvas.onmouseup = () => {
      const imagedata: imagedata = context.getimagedata(0, 0, canvas.width, canvas.height)

      // 如果此时处于撤销状态,此时再使用画笔,则将之后的状态清空,以刚画的作为最新的画布状态
      if (canvascurrenthistory < canvashistroylistref.current.length) {
        canvashistroylistref.current = canvashistroylistref.current.slice(0, canvascurrenthistory)
      }
      canvashistroylistref.current.push(imagedata)
      setcanvascurrenthistory(canvascurrenthistory + 1)
      context.closepath()
      canvas.onmousemove = null
      canvas.onmouseup = null
    }
  }

  const handlemovemode = (downx: number, downy: number) => {
    const { current: canvas } = canvasref
    const { current: wrap } = wrapref
    const { current: fillstartpointx } = fillstartpointxref
    const { current: fillstartpointy } = fillstartpointyref
    if (!canvas || !wrap || mousemode !== 0) return

    // 为容器添加移动事件,可以在空白处移动图片
    wrap.onmousemove = (event: mouseevent) => {
      const movex: number = event.pagex
      const movey: number = event.pagey

      translatepointxref.current = fillstartpointx + (movex - downx)
      translatepointyref.current = fillstartpointy + (movey - downy)

      canvas.style.transform = `scale(${canvasscale},${canvasscale}) translate(${translatepointxref.current}px,${translatepointyref.current}px)`
    }

    wrap.onmouseup = (event: mouseevent) => {
      const upx: number = event.pagex
      const upy: number = event.pagey

      wrap.onmousemove = null
      wrap.onmouseup = null;

      fillstartpointxref.current = fillstartpointx + (upx - downx)
      fillstartpointyref.current = fillstartpointy + (upy - downy)
    }
  }

  // 目前橡皮擦还有点问题,前端显示正常,保存图片下来,擦除的痕迹会变成白色
  const handleerasermode = (downx: number, downy: number) => {
    const { current: canvas } = canvasref
    const { current: wrap } = wrapref
    const context: canvasrenderingcontext2d | undefined | null = canvas?.getcontext('2d')
    if (!canvas || !wrap || !context) return

    const offsetleft: number = canvas.offsetleft
    const offsettop: number = canvas.offsettop
    downx = downx - offsetleft
    downy = downy - offsettop

    const { pointx, pointy } = generatelinepoint(downx, downy)

    context.beginpath()
    context.moveto(pointx, pointy)

    canvas.onmousemove = null
    canvas.onmousemove = (event: mouseevent) => {
      const movex: number = event.pagex - offsetleft
      const movey: number = event.pagey - offsettop
      const { pointx, pointy } = generatelinepoint(movex, movey)
      context.globalcompositeoperation = "destination-out"
      context.linewidth = linewidth
      context.lineto(pointx, pointy)
      context.stroke()
    }
    canvas.onmouseup = () => {
      const imagedata: imagedata = context.getimagedata(0, 0, canvas.width, canvas.height)
      if (canvascurrenthistory < canvashistroylistref.current.length) {
        canvashistroylistref.current = canvashistroylistref.current.slice(0, canvascurrenthistory)
      }
      canvashistroylistref.current.push(imagedata)
      setcanvascurrenthistory(canvascurrenthistory + 1)
      context.closepath()
      canvas.onmousemove = null
      canvas.onmouseup = null
    }
  }

  const handlecanvas = () => {
    const { current: canvas } = canvasref
    const { current: wrap } = wrapref
    const context: canvasrenderingcontext2d | undefined | null = canvas?.getcontext('2d')
    if (!context || !wrap) return

    // 清除上一次设置的监听,以防获取参数错误
    wrap.onmousedown = null
    wrap.onmousedown = function (event: mouseevent) {
      const downx: number = event.pagex
      const downy: number = event.pagey

      switch (mousemode) {
        case move_mode:
          handlemovemode(downx, downy)
          break
        case line_mode:
          handlelinemode(downx, downy)
          break
        case eraser_mode:
          handleerasermode(downx, downy)
          break
        default:
          break
      }
    }

    wrap.onwheel = null
    wrap.onwheel = (e: mousewheelevent) => {
      const { deltay } = e
      const newscale: number = deltay > 0
        ? (canvasscale * 10 - 0.1 * 10) / 10
        : (canvasscale * 10 + 0.1 * 10) / 10
      if (newscale < 0.1 || newscale > 2) return
      setcanvasscale(newscale)
    }
  }

  const handlescalechange = (value: number) => {
    setcanvasscale(value)
  }

  const handlelinewidthchange = (value: number) => {
    setlinewidth(value)
  }

  const handlecolorchange = (color: string) => {
    setlinecolor(color)
  }

  const handlemousemodechange = (event: radiochangeevent) => {
    const { target: { value } } = event
    const { current: canvas } = canvasref
    const { current: wrap } = wrapref

    setmousemode(value)

    if (!canvas || !wrap) return
    switch (value) {
      case move_mode:
        canvas.style.cursor = 'move'
        wrap.style.cursor = 'move'
        break
      case line_mode:
        canvas.style.cursor = `url('http://cdn.algbb.cn/pencil.ico') 6 26, pointer`
        wrap.style.cursor = 'default'
        break
      case eraser_mode:
        message.warning('橡皮擦功能尚未完善,保存图片会出现错误')
        canvas.style.cursor = `url('http://cdn.algbb.cn/eraser.ico') 6 26, pointer`
        wrap.style.cursor = 'default'
        break
      default:
        canvas.style.cursor = 'default'
        wrap.style.cursor = 'default'
        break
    }
  }

  const handlesaveclick = () => {
    const { current: canvas } = canvasref
    // 可存入数据库或是直接生成图片
    console.log(canvas?.todataurl())
  }

  const handlepaperchange = (value: string) => {
    const fillimagelist = {
      'xueshengjia': 'http://cdn.algbb.cn/test/canvastest.jpg',
      'xueshengyi': 'http://cdn.algbb.cn/test/canvastest2.png',
      'xueshengbing': 'http://cdn.algbb.cn/emoji/30.png',
    }
    setfillimagesrc(fillimagelist[value])
  }

  const handlerollback = () => {
    const isfirsthistory: boolean = canvascurrenthistory === 1
    if (isfirsthistory) return
    setcanvascurrenthistory(canvascurrenthistory - 1)
  }

  const handlerollforward = () => {
    const { current: canvashistroylist } = canvashistroylistref
    const islasthistory: boolean = canvascurrenthistory === canvashistroylist.length
    if (islasthistory) return
    setcanvascurrenthistory(canvascurrenthistory + 1)
  }

  const handleclearcanvasclick = () => {
    const { current: canvas } = canvasref
    const context: canvasrenderingcontext2d | undefined | null = canvas?.getcontext('2d')
    if (!canvas || !context || canvascurrenthistory === 0) return

    // 清空画布历史
    canvashistroylistref.current = [canvashistroylistref.current[0]]
    setcanvascurrenthistory(1)

    message.success('画布清除成功!')
  }

  return (
    <div>
      <custombreadcrumb list={['内容管理', '批阅作业']} />
      <div classname="mark-paper__container" ref={containerref}>
        <div classname="mark-paper__wrap" ref={wrapref}>
          <div
            classname="mark-paper__mask"
            style={{ display: isloading ? 'flex' : 'none' }}
          >
            <spin
              tip="图片加载中..."
              indicator={<icon type="loading" style={{ fontsize: 36 }} spin
              />}
            />
          </div>
          <canvas
            ref={canvasref}
            classname="mark-paper__canvas">
            <p>很可惜,这个东东与您的电脑不搭!</p>
          </canvas>
        </div>
        <div classname="mark-paper__sider">
          <div>
            选择作业:
            <select
              defaultvalue="xueshengjia"
              style={{
                width: '100%', margin: '10px 0 20px 0'
              }}
              onchange={handlepaperchange} >
              <optgroup label="17软件一班">
                <option value="xueshengjia">学生甲</option>
                <option value="xueshengyi">学生乙</option>
              </optgroup>
              <optgroup label="17软件二班">
                <option value="xueshengbing">学生丙</option>
              </optgroup>
            </select>
          </div>
          <div>
            画布操作:<br />
            <div classname="mark-paper__action">
              <tooltip title="撤销">
                <i
                  classname={`icon iconfont icon-chexiao ${canvascurrenthistory <= 1 && 'disable'}`}
                  onclick={handlerollback} />
              </tooltip>
              <tooltip title="恢复">
                <i
                  classname={`icon iconfont icon-fanhui ${canvascurrenthistory >= canvashistroylistref.current.length && 'disable'}`}
                  onclick={handlerollforward} />
              </tooltip>
              <popconfirm
                title="确定清空画布吗?"
                onconfirm={handleclearcanvasclick}
                oktext="确定"
                canceltext="取消"
              >
                <tooltip title="清空">
                  <i classname="icon iconfont icon-qingchu" />
                </tooltip>
              </popconfirm>
            </div>
          </div>
          <div>
            画布缩放:
            <tooltip placement="top" title='可用鼠标滚轮进行缩放'>
              <icon type="question-circle" />
            </tooltip>
            <slider
              min={0.1}
              max={2.01}
              step={0.1}
              value={canvasscale}
              tipformatter={(value) => `${(value).tofixed(2)}x`}
              onchange={handlescalechange} />
          </div>
          <div>
            画笔大小:
            <slider
              min={1}
              max={9}
              value={linewidth}
              tipformatter={(value) => `${value}px`}
              onchange={handlelinewidthchange} />
          </div>
          <div>
            模式选择:
            <radio.group
              classname="radio-group"
              onchange={handlemousemodechange}
              value={mousemode}>
              <radio value={0}>移动</radio>
              <radio value={1}>画笔</radio>
              <radio value={2}>橡皮擦</radio>
            </radio.group>
          </div>
          <div>
            颜色选择:
            <div classname="color-picker__container">
              {['#fa4b2a', '#ffff00', '#ee00ee', '#1890ff', '#333333', '#ffffff'].map(color => {
                return (
                  <tooltip placement="top" title={color} key={color}>
                    <div
                      role="button"
                      classname={`color-picker__wrap ${color === linecolor && 'color-picker__wrap--active'}`}
                      style={{ background: color }}
                      onclick={() => handlecolorchange(color)}
                    />
                  </tooltip>
                )
              })}
            </div>
          </div>
          <button onclick={handlesaveclick}>保存图片</button>
        </div>
      </div>
    </div >
  )
}

export default markpaper as componenttype

总结

到此这篇关于html5 canvas实现图片标记、缩放、移动和保存历史状态 (附转换公式)的文章就介绍到这了,更多相关canvas 图片标记 缩放 移动内容请搜索以前的文章或继续浏览下面的相关文章,希望大家以后多多支持!