image.png
在反饋組件中寺晌,需要一個(gè)網(wǎng)頁(yè)自由截圖功能。
現(xiàn)成的輪子澡刹,沒(méi)有找到合適的呻征。可能因?yàn)樽杂山貓D的需求比較少罢浇。
想到了比較常用的html2canvas
:
take "screenshots" of webpages or parts of it, directly on the users browser.
使用html2canvas
陆赋,只要搞定用戶(hù)需要的是哪個(gè)部分,就可以完成自由截圖了嚷闭。
最終的目的是拿到截取圖片的寬高和xy偏移量攒岛。
思路:通過(guò)監(jiān)聽(tīng)mousedown
mousemove
mouseup
事件,記錄起始點(diǎn)坐標(biāo)凌受。
細(xì)節(jié) 1. mousemove
需要防抖處理阵子。
2. 需要考慮結(jié)束點(diǎn)在起始點(diǎn)上下左右各個(gè)方位的情況。
3. 截取時(shí)胜蛉,需要高亮選中區(qū)域挠进,用起始點(diǎn)坐標(biāo)確定四個(gè)遮罩區(qū)域進(jìn)行拼接色乾。
4. 截取完成,需要顯示controls
领突,要根據(jù)起始點(diǎn)與頁(yè)面邊緣的距離考慮controls
的顯示位置暖璧。
const [clipStartPoint, setClipStartPoint] = useState({});//起點(diǎn)
const [clipEndPoint, setClipEndPoint] = useState({});//終點(diǎn)
const [showClipPart,setShowClipPart]= useState(false);//是否顯示遮罩區(qū)域(高亮)
const [configVisible,setConfigVisible]= useState(false);//是否顯示controls
const [makingImg,setMakingImg]= useState(false);//生成截圖
html2canvas(document.body,{
width:width,
height:height,
x:x,
y:y
}).then(function(canvas) {
onSuccess(canvas.toDataURL('image/png'));
});
后續(xù),可以結(jié)合Canvas繪圖功能君旦,在controls
中增加繪制功能澎办,類(lèi)似常用的微信截圖功能。