开篇
最近在做一个图片截图的功能。
因为工作时间很紧张,
当时是使用的是一个截图插件。
周末两天无所事事,来写一个简单版本的截图功能。
因为写的比较简单,如果写的不好,求大佬轻一点喷
读取图片并获取图片的宽度和高度思路
首先读取文件我们使用input中类型是file。
我们需要对读取的对象进行限制,必须是图片类型。
这个可以使用这个属性:accept="image/*" 来实现
但是这个属性不可靠,最好还是通过正则来判断。
我们要获取图片的宽和高,需要创建FileReader对象。
使用reader.readAsDataURL(file)异步读取文件内容,
并将其编码为一个Data URL(数据URL)
当文件读取完成之后,会触发reader.onload事件。
这个时候我们还要创建一个图片对象。
等待这个图片读取完成后,通过 img.width, img.height返回图片的宽和高。
下面我们就来简单实现一下
读取图片并获取图片的宽度
<div>
<input type="file" id="file" accept="image/*" />
</div>
<script>
let fileNode = document.getElementById("file")
fileNode.addEventListener("change", readFile)
function readFile(e){
let file = e.target.files[0]
getImageWH(file, function(width, height) {
console.log('Width:', width, 'Height:', height);
});
}
function getImageWH(file, callback) {
const reader = new FileReader();
reader.onload = function(e) {
console.log('e这个对象', e)
const img = new Image();
img.src = e.target.result;
img.onload = function() {
callback(img.width, img.height);
};
};
reader.readAsDataURL(file);
}
</script>
将图片的宽高赋值给canvas
我们在获取图片的宽和高之后然后赋值给canvas。
并且将canvas给显示出来就行。
这一步比较简单
<style>
.canvas-box{
border: 1px solid red;
display: none;
}</style><canvas id="canvas-node" class="canvas-box"></canvas>
let canvasNode = document.getElementById("canvas-node")function readFile(e){
let file = e.target.files[0]
getImageWH(file, function(width, height) {
canvasSetWH(canvasNode,width, height)
});
}function canvasSetWH(canvasNode,width, height){
canvasNode.width = width
canvasNode.height = height
canvasNode.style.display = "block"}
将图片内容在canvas中显示出来
想要将图片绘制出来,此时我们需要借助drawImage这个API。
这个API有三种形式的传参第1种:drawImage(image, x, y)image: 绘制的图像源x, y: 图像在画布上的起始坐标(x,y), 图像将以原始尺寸绘制第2种:drawImage(image, x, y, width, height)image: 绘制的图像源x, y: 图像在画布上的起始坐标(x,y)
width, height(可选):绘制到画布上的图像的宽度和高度第3种: drawImage(image, sx, sy, swidth, sheight, dx, dy, dwidth, dheight)image: 绘制的图像源
sx, sy: 图像源中矩形区域的起始坐标
swidth, sheight:图像源中矩形区域的宽度和高度,即要绘制的图像部分
dx, dy:绘制到画布上的起始坐标
dwidth, dheight:绘制到画布上的矩形区域的宽度和高度,允许对绘制的图像进行缩放也就是说:我们这里绘制可以使用第1种方法和第2种方法。图像源在getImageWH 这个方法中返回来。
function getImageWH(file, callback) {
reader.onload = function(e) {
img.onload = function() {
callback(img,img.width, img.height);
};
};
reader.readAsDataURL(file);
}
let canvasNode = document.getElementById("canvas-node")let ctx = canvasNode.getContext("2d")function readFile(e){
let file = e.target.files[0]
getImageWH(file, function(img, width, height) {
canvasSetWH(canvasNode,width, height)
ctx.drawImage(img, 0, 0,width, height );
});
}
绘制蒙层
绘制蒙层这一步相对比较简单。
我们只需要在图片上绘制一个跟图片大小一样的蒙层即可。
可以借助fillStyle来填充颜色。fillRect绘制矩形。
下面我们简单实现一下
drawMask(0,0,width, height);function drawMask(x, y, width, height, opactity) {
ctx.fillStyle = "rgba(0,0,0,0.5)";
ctx.fillRect(x, y, width, height);
}
绘制截图区域
我们需要给canvas绑定鼠标按下事件。
在鼠标按下的时候记录上当前鼠标的坐标信息(x,y)
在鼠标按下的时候还要注册移动事件和抬起事件。
在鼠标移动的时候计算出蒙层的位置信息(rectEndX,rectEndY)
然后计算出截图区域的位置信息
最后还需要鼠标抬起的时候要移除移动事件和抬起事件
下面我们来简单实现一下
.... 其他代码.....let img = new Image();canvasNode.addEventListener("mousedown", mousedownInCanvasHandler)let currentPoint = {}function mousedownInCanvasHandler(e){
currentPoint= { x: e.offsetX, y: e.offsetY }
canvasNode.addEventListener('mousemove', mousemoveInCanvasHandler)
canvasNode.addEventListener('mouseup', mouseupInCanvasHandler)
}function mousemoveInCanvasHandler(e){
let rectEndX = e.offsetX
let rectEndY = e.offsetY
let rectWidth = rectEndX - currentPoint.x
let rectHeight = rectEndY - currentPoint.y
let {width, height} = canvasNode
ctx.clearRect(0, 0, width, height)
drawMask(0,0,width, height);
drawScreenShot(width, height,rectWidth, rectHeight)
}function drawScreenShot( canvasWidth, canvasHeight,rectWidth,rectHeight){
ctx.globalCompositeOperation = "destination-out";
ctx.fillStyle='#000'
ctx.fillRect(currentPoint.x, currentPoint.y,rectWidth,rectHeight)
ctx.globalCompositeOperation ='destination-over'
ctx.drawImage(img, 0, 0,canvasWidth, canvasHeight,0,0,canvasWidth, canvasHeight );
}function mouseupInCanvasHandler(e){
canvasNode.removeEventListener('mousemove', mousemoveInCanvasHandler)
canvasNode.removeEventListener('mouseup', mouseupInCanvasHandler)
}
.... 其他代码.....
把截图的区域显示出来
我们只需要在截图完成后(鼠标抬起时)
得到截图区域的信息ctx.getImageData()
然后把截图区域的信息写入一个新的画布即可。
在绘制前先清空画布
<style>
.canvas-box,.canvas2-box{
display: none;
}
</style><body>
<div>
<input type="file" id="file" accept="image/*" />
</div>
<canvas id="canvas-node" class="canvas-box"></canvas>
<div class="canvas2-box">
<canvas id="canvas2"></canvas>
</div></body>screenshotData= [currentPoint.x, currentPoint.y, rectWidth, rectHeight]function mouseupInCanvasHandler(e){
canvasNode.removeEventListener('mousemove', mousemoveInCanvasHandler)
canvasNode.removeEventListener('mouseup', mouseupInCanvasHandler)
drawScreenShotImg(screenshotData)
}function drawScreenShotImg(screenshotData){
let drawData = ctx.getImageData(...screenshotData)
canvasSetWH(canvas2Box,screenshotData[2],screenshotData[3])
ctx2.clearRect(0,0, currentPoint.x, currentPoint.y)
ctx2.putImageData(drawData,0,0)
}
将截图区域的部分下载下来
将canvas下载下来时,需要借助
语法:canvas.toDataURL(picType, encoderOptions)
参数:
picType:表示的是图片的格式。默认为 image/png。
encoderOptions:从 0 到 1 的区间内选择图片的质量。
如果超出取值范围,将会使用默认值 0.92。其他参数会被忽略。
获取图片的类型我们可以通过(file.type)来知道
let file = e.target.files[0]fileType = file.type
<button id="downBtn">down</button>
downBtn.addEventListener('click',()=>{
let {width, height} = canvas2
let imgURL = canvas2.toDataURL( fileType, 1);
let link = document.createElement('a');
link.download = "截图图片";
link.href = imgURL;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
截图功能全部代码
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>canvas实现截图功能</title>
<style>
.canvas-box,.canvas2-box{
display: none;
}
</style></head><body>
<div>
<input type="file" id="file" accept="image/*" />
</div>
<canvas id="canvas-node" class="canvas-box"></canvas>
<button id="downBtn">down</button>
<div class="canvas2-box">
<canvas id="canvas2"></canvas>
</div></body><script>
let canvasNode = document.getElementById("canvas-node")
let ctx = canvasNode.getContext("2d")
let downBtn = document.getElementById("downBtn")
let canvas2Box = document.querySelector(".canvas2-box")
let canvas2 = document.getElementById("canvas2")
let ctx2 = canvas2.getContext("2d")
let fileNode = document.getElementById("file")
fileNode.addEventListener("change", readFile)
let img = new Image();
let screenshotData = []
let fileType = ""
canvasNode.addEventListener("mousedown", mousedownInCanvasHandler)
let currentPoint = {}
downBtn.addEventListener('click',()=>{
let {width, height} = canvas2
let imgURL = canvas2.toDataURL( fileType, 1);
let link = document.createElement('a');
link.download = "截图图片";
link.href = imgURL;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
function mousedownInCanvasHandler(e){
currentPoint= { x: e.offsetX, y: e.offsetY }
canvasNode.addEventListener('mousemove', mousemoveInCanvasHandler)
canvasNode.addEventListener('mouseup', mouseupInCanvasHandler)
}
function mousemoveInCanvasHandler(e){
let rectEndX = e.offsetX
let rectEndY = e.offsetY
let rectWidth = rectEndX - currentPoint.x
let rectHeight = rectEndY - currentPoint.y
let {width, height} = canvasNode
screenshotData= [currentPoint.x, currentPoint.y, rectWidth, rectHeight]
ctx.clearRect(0, 0, width, height)
drawMask(0,0,width, height);
drawScreenShot(width, height,rectWidth, rectHeight)
}
function drawScreenShot( canvasWidth, canvasHeight,rectWidth,rectHeight){
ctx.globalCompositeOperation = "destination-out";
ctx.fillStyle='#000'
ctx.fillRect(currentPoint.x, currentPoint.y,rectWidth,rectHeight)
ctx.globalCompositeOperation ='destination-over'
ctx.drawImage(img, 0, 0,canvasWidth, canvasHeight,0,0,canvasWidth, canvasHeight );
}
function mouseupInCanvasHandler(e){
canvasNode.removeEventListener('mousemove', mousemoveInCanvasHandler)
canvasNode.removeEventListener('mouseup', mouseupInCanvasHandler)
drawScreenShotImg(screenshotData)
}
function drawScreenShotImg(screenshotData){
let drawData = ctx.getImageData(...screenshotData)
canvasSetWH(canvas2Box,screenshotData[2],screenshotData[3])
ctx2.clearRect(0,0, currentPoint.x, currentPoint.y)
ctx2.putImageData(drawData,0,0)
}
function readFile(e){
let file = e.target.files[0]
console.log('file.type', file.type)
fileType = file.type
getImageWH(file, function(width, height) {
canvasSetWH(canvasNode,width, height)
ctx.drawImage(img, 0, 0,width, height );
drawMask(0,0,width, height);
});
}
function getImageWH(file, callback) {
const reader = new FileReader();
reader.onload = function(e) {
console.log('e这个对象', e)
img.src = e.target.result;
img.onload = function() {
callback(img.width, img.height);
};
};
reader.readAsDataURL(file);
}
function canvasSetWH(canvasNode,width, height){
canvasNode.width = width
canvasNode.height = height
canvasNode.style.display = "block"
}
function drawMask(x, y, width, height, opactity) {
ctx.fillStyle = "rgba(0,0,0,0.5)";
ctx.fillRect(x, y, width, height);
}</script></html>
作者:晚来南风晚相识
出处:https://www.cnblogs.com/IwishIcould/
该文章在 2024/10/18 10:29:24 编辑过