開(kāi)篇
最近在做一個(gè)圖片截圖的功能。
因?yàn)楣ぷ鲿r(shí)間很緊張,
當(dāng)時(shí)是使用的是一個(gè)截圖插件。
周末兩天無(wú)所事事,來(lái)寫(xiě)一個(gè)簡(jiǎn)單版本的截圖功能。
因?yàn)閷?xiě)的比較簡(jiǎn)單,如果寫(xiě)的不好,求大佬輕一點(diǎn)噴
讀取圖片并獲取圖片的寬度和高度思路
首先讀取文件我們使用input中類型是file。
我們需要對(duì)讀取的對(duì)象進(jìn)行限制,必須是圖片類型。
這個(gè)可以使用這個(gè)屬性:accept="image/*" 來(lái)實(shí)現(xiàn)
但是這個(gè)屬性不可靠,最好還是通過(guò)正則來(lái)判斷。
我們要獲取圖片的寬和高,需要?jiǎng)?chuàng)建FileReader對(duì)象。
使用reader.readAsDataURL(file)異步讀取文件內(nèi)容,
并將其編碼為一個(gè)Data URL(數(shù)據(jù)URL)
當(dāng)文件讀取完成之后,會(huì)觸發(fā)reader.onload事件。
這個(gè)時(shí)候我們還要?jiǎng)?chuàng)建一個(gè)圖片對(duì)象。
等待這個(gè)圖片讀取完成后,通過(guò) img.width, img.height返回圖片的寬和高。
下面我們就來(lái)簡(jiǎn)單實(shí)現(xiàn)一下
讀取圖片并獲取圖片的寬度
<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這個(gè)對(duì)象', e)
const img = new Image();
img.src = e.target.result;
img.onload = function() {
callback(img.width, img.height);
};
};
reader.readAsDataURL(file);
}
</script>
將圖片的寬高賦值給canvas
我們?cè)讷@取圖片的寬和高之后然后賦值給canvas。
并且將canvas給顯示出來(lái)就行。
這一步比較簡(jiǎn)單
<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"}
將圖片內(nèi)容在canvas中顯示出來(lái)
想要將圖片繪制出來(lái),此時(shí)我們需要借助drawImage這個(gè)API。
這個(gè)API有三種形式的傳參第1種:drawImage(image, x, y)image: 繪制的圖像源x, y: 圖像在畫(huà)布上的起始坐標(biāo)(x,y), 圖像將以原始尺寸繪制第2種:drawImage(image, x, y, width, height)image: 繪制的圖像源x, y: 圖像在畫(huà)布上的起始坐標(biāo)(x,y)
width, height(可選):繪制到畫(huà)布上的圖像的寬度和高度第3種: drawImage(image, sx, sy, swidth, sheight, dx, dy, dwidth, dheight)image: 繪制的圖像源
sx, sy: 圖像源中矩形區(qū)域的起始坐標(biāo)
swidth, sheight:圖像源中矩形區(qū)域的寬度和高度,即要繪制的圖像部分
dx, dy:繪制到畫(huà)布上的起始坐標(biāo)
dwidth, dheight:繪制到畫(huà)布上的矩形區(qū)域的寬度和高度,允許對(duì)繪制的圖像進(jìn)行縮放也就是說(shuō):我們這里繪制可以使用第1種方法和第2種方法。圖像源在getImageWH 這個(gè)方法中返回來(lái)。
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 );
});
}
繪制蒙層
繪制蒙層這一步相對(duì)比較簡(jiǎn)單。
我們只需要在圖片上繪制一個(gè)跟圖片大小一樣的蒙層即可。
可以借助fillStyle來(lái)填充顏色。fillRect繪制矩形。
下面我們簡(jiǎn)單實(shí)現(xiàn)一下
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);
}
繪制截圖區(qū)域
我們需要給canvas綁定鼠標(biāo)按下事件。
在鼠標(biāo)按下的時(shí)候記錄上當(dāng)前鼠標(biāo)的坐標(biāo)信息(x,y)
在鼠標(biāo)按下的時(shí)候還要注冊(cè)移動(dòng)事件和抬起事件。
在鼠標(biāo)移動(dòng)的時(shí)候計(jì)算出蒙層的位置信息(rectEndX,rectEndY)
然后計(jì)算出截圖區(qū)域的位置信息
最后還需要鼠標(biāo)抬起的時(shí)候要移除移動(dòng)事件和抬起事件
下面我們來(lái)簡(jiǎn)單實(shí)現(xiàn)一下
.... 其他代碼.....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)
}
.... 其他代碼.....
把截圖的區(qū)域顯示出來(lái)
我們只需要在截圖完成后(鼠標(biāo)抬起時(shí))
得到截圖區(qū)域的信息ctx.getImageData()
然后把截圖區(qū)域的信息寫(xiě)入一個(gè)新的畫(huà)布即可。
在繪制前先清空畫(huà)布
<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)
}
將截圖區(qū)域的部分下載下來(lái)
將canvas下載下來(lái)時(shí),需要借助
語(yǔ)法:canvas.toDataURL(picType, encoderOptions)
參數(shù):
picType:表示的是圖片的格式。默認(rèn)為 image/png。
encoderOptions:從 0 到 1 的區(qū)間內(nèi)選擇圖片的質(zhì)量。
如果超出取值范圍,將會(huì)使用默認(rèn)值 0.92。其他參數(shù)會(huì)被忽略。
獲取圖片的類型我們可以通過(guò)(file.type)來(lái)知道
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實(shí)現(xiàn)截圖功能</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這個(gè)對(duì)象', 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>
作者:晚來(lái)南風(fēng)晚相識(shí)
出處:https://www.cnblogs.com/IwishIcould/
該文章在 2024/10/18 10:29:24 編輯過(guò)