话不多说,先看下效果
在截图开始后,在【canvas A】的mousedown事件记录起点坐标 A, 通过mousemove事件实时监听具体的坐标,document 级的mouseup事件记录结束坐标 B(鼠标有可能会跑出截图区域外,所以是在 document 上监听 mouseup),以 A 为起点,B 为终点,AB 两点就能够计算出截取区域
// 获取截图开始的点
【canvas A】.onmousedown = function (e) {
记录起点坐标A
}
// 获取鼠标坐标
【canvas A】.onmousemove = function (坐标数据) {
1. 记录鼠标坐标
2. 生成截图区域动效
}
// 获取截图结束的点
document.addEventListener('mouseup', function (e) {
1.记录终点坐标
2. 生成截图()
}
在mousedown事件上把【canvas A】给置灰
// 设置截图时灰色背景
【canvas A】.fillStyle = 'rgba(0,0,0,0.6)'
【canvas A】.strokeStyle = 'rgba(0,143,255,1)'
在mouseup事件上绘制被截取效果
fillRect(0, 0, 【canvas A】.width, 【canvas A】.height)
那就是把我们之前设置好置灰样式在目标图片上层进行绘制,实现了第一步置灰效果【canvas A】.fillRect(x, y, w, h)
使得截取内部透明 //第一步:遮罩层
【canvas A】.globalCompositeOperation = 'source-over'
【canvas A】.fillRect(0, 0, 【canvas A】.width, 【canvas A】.height)
//第二步:画框
【canvas A】.globalCompositeOperation = 'destination-out'
【canvas A】.fillRect(x, y, w, h)
//第三步:描边
【canvas A】.globalCompositeOperation = 'source-over'
【canvas A】.moveTo(x, y)
【canvas A】.lineTo(x + w, y)
【canvas A】.lineTo(x + w, y + h)
【canvas A】.lineTo(x, y + h)
【canvas A】.lineTo(x, y)
【canvas A】.stroke()
【canvas A】.closePath()
鼠标动作停止后就是截图结束,所以需要在moveup事件生成截取图片数据,在这里可以通过 canvas 自带的 canvas.toDataURL 把截图转化为 base64,因为通过mousedown和mousemove我们已经获取用户的截取区域了,并且我们在截图开始的时候,会把原图片绘制到【canvas B】中,所以我们可以直接在【canvas B】上对该区域进行截取然后生成图片~
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
const data = 【canvas B】.getImageData(area.x, area.y, area.w, area.h)
canvas.width = area.w
canvas.height = area.h
context.putImageData(data, 0, 0)
return canvas.toDataURL('image/png', 1)
我已经把截图功能封装成了一个 hook,有需要自取。还比较糙,有问题随时反馈。
这个 hook 会返回三个函数 init, cut, cancelCut,以及截图数据 clipImgData,
const clip = () => {
const clipAreaWrap = useRef(null) // 截图区域dom
const clipCanvas = useRef(null) // 用于截图的的canvas,以及截图开始生成截图效果(背景置灰)
const drawCanvas = useRef(null) // 把图片绘制到canvas上方便 用于生成截取图片的base64数据
const [clipImgData, setClipImgData] = useState('')
const init = (wrap) => {
if (!wrap) return
clipAreaWrap.current = wrap
clipCanvas.current = document.createElement('canvas')
drawCanvas.current = document.createElement('canvas')
clipCanvas.current.style =
'width:100%;height:100%;z-index: 2;position: absolute;left: 0;top: 0;'
drawCanvas.current.style =
'width:100%;height:100%;z-index: 1;position: absolute;left: 0;top: 0;'
clipAreaWrap.current.appendChild(clipCanvas.current)
clipAreaWrap.current.appendChild(drawCanvas.current)
}
// 截图
const cut = (souceImg: string) => {
const drawCanvasCtx = drawCanvas.current.getContext('2d')
const clipCanvasCtx = clipCanvas.current.getContext('2d')
const wrapWidth = clipAreaWrap.current.clientWidth
const wrapHeight = clipAreaWrap.current.clientHeight
clipCanvas.current.width = wrapWidth
clipCanvas.current.height = wrapHeight
drawCanvas.current.width = wrapWidth
drawCanvas.current.height = wrapHeight
// 设置截图时灰色背景
clipCanvasCtx.fillStyle = 'rgba(0,0,0,0.6)'
clipCanvasCtx.strokeStyle = 'rgba(0,143,255,1)'
// 生成一个截取区域的img 然后把它作为canvas的第一个参数
const clipImg = document.createElement('img')
clipImg.classList.add('img_anonymous')
clipImg.crossOrigin = 'anonymous'
clipImg.src = souceImg
// Q: 这里为什么需要append到clipAreaWrap里
// A: 因为直接clipImg.src的引入是没有css样式的(主要是宽高)如果不append直接进行drawCanvasCtx.drawImage,
// 那其实画的是原始大小的clipImg
clipAreaWrap.current.appendChild(clipImg)
// 绘制截图区域
clipImg.onload = () => {
// x,y -> 计算从drawCanvasCtx的的哪一x,y坐标点进行绘制
const x = Math.floor((wrapWidth - clipImg.width) / 2)
const y = Math.floor((wrapHeight - clipImg.height) / 2)
// Q: 为什么这里要用克隆节点的宽高
// A: 因为clipImg的宽高是在dom中已经被css修改过的宽高(长/宽)了,而非该图片的真实长和宽
// 用这个宽高在drawCanvasCtx的绘图只会绘制clipImg的小部分内容(因为假宽高比真宽高小),看起来就像是被放大了
const clipImgCopy = clipImg.cloneNode()
drawCanvasCtx.drawImage(
clipImg,
0,
0,
clipImgCopy.width,
clipImgCopy.height,
x,
y,
clipImg.width,
clipImg.height
)
}
let start = null
// 获取截图开始的点
clipCanvas.current.onmousedown = function (e) {
start = {
x: e.offsetX,
y: e.offsetY
}
}
// 绘制截图区域效果
clipCanvas.current.onmousemove = function (e) {
if (start) {
fill(
clipCanvasCtx,
wrapWidth,
wrapHeight,
start.x,
start.y,
e.offsetX - start.x,
e.offsetY - start.y
)
}
}
// 截图完毕,获取截图图片数据
document.addEventListener('mouseup', function (e) {
if (start) {
var url = getClipPicUrl(
{
x: start.x,
y: start.y,
w: e.offsetX - start.x,
h: e.offsetY - start.y
},
drawCanvasCtx
)
start = null
//生成base64格式的图
setClipImgData(url)
}
})
}
const cancelCut = () => {
clipCanvas.current.width = clipAreaWrap.current.clientWidth
clipCanvas.current.height = clipAreaWrap.current.clientHeight
drawCanvas.current.width = clipAreaWrap.current.clientWidth
drawCanvas.current.height = clipAreaWrap.current.clientHeight
const drawCanvasCtx = drawCanvas.current.getContext('2d')
const clipCanvasCtx = clipCanvas.current.getContext('2d')
drawCanvasCtx.clearRect(
0,
0,
drawCanvas.current.clientWidth,
drawCanvas.current.clientHeight
)
clipCanvasCtx.clearRect(
0,
0,
clipCanvas.current.clientWidth,
clipCanvas.current.clientHeight
)
//移除鼠标事件
clipCanvas.current.onmousedown = null
clipCanvas.current.onmousemove = null
}
const getClipPicUrl = (area, drawCanvasCtx) => {
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
const data = drawCanvasCtx.getImageData(area.x, area.y, area.w, area.h)
canvas.width = area.w
canvas.height = area.h
context.putImageData(data, 0, 0)
return canvas.toDataURL('image/png', 1)
}
// 绘制出截图的效果
const fill = (context, ctxWidth, ctxHeight, x, y, w, h) => {
context.clearRect(0, 0, ctxWidth, ctxHeight)
context.beginPath()
//遮罩层
context.globalCompositeOperation = 'source-over'
context.fillRect(0, 0, ctxWidth, ctxHeight)
//画框
context.globalCompositeOperation = 'destination-out'
context.fillRect(x, y, w, h)
//描边
context.globalCompositeOperation = 'source-over'
context.moveTo(x, y)
context.lineTo(x + w, y)
context.lineTo(x + w, y + h)
context.lineTo(x, y + h)
context.lineTo(x, y)
// context.stroke()
context.closePath()
}
return { init, cut, cancelCut, clipImgData }
}
import React, { ReactElement, useEffect, useRef, useState } from 'react'
import './index.less'
export default () => {
const clipAreaWrap = useRef(null) // 截图区域dom
const { init, cut, cancelCut, clipImgData } = clip()
return (
<>
<div className="clip-area-wrap" ref={clipAreaWrap}>
<img
className="clip-area-example"
src={require('../../assets/img/pet/cat-all.png')}
alt=""
/>
</div>
<div className="clip-img-area">
<img src={clipImgData} alt="" id="img" />
</div>
<div className="operation">
<button
onClick={() => {
init(clipAreaWrap.current)
cut(
'https://cdn-tos.baohuaxia.com/obj/static-assets/433ed21f7f4a27a5bde94a8119d618c5.png'
)
}}
>
截图
</button>
<button
onClick={() => {
cancelCut()
}}
>
取消
</button>
</div>
</>
)
}
.clip-area-wrap {
height: 450px;
position: relative;
//图片居中显示
img {
width: 100%;
display: block;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
max-width: 100%;
max-height: 100%;
}
}
//回显区域
.clip-img-area {
width: 250px;
height: 250px;
position: relative;
margin: 0 auto;
//图片居中显示
img {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
max-width: 100%;
max-height: 100%;
}
}
后续还想实现一些功能,比如:
文章会持续更新,敬请关注
canvas 实现截图功能——截取图片的一部分[1]
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8