使用html2canvas庫實現一個簡單截圖功能,還需優化

  之前興趣寫的一個簡單html截圖功能,如今分享出來,參考。javascript

  使用html2canvas庫實現,功能簡單,待優化。。。css

  效果圖:html

   

 

功能簡單,代碼也簡單。。java

一、須要html2canvas庫,本身找個或者在下面下載node

二、主要實現代碼SnippingTool.jsjquery

/**
 * Create by 廣信-zhoujie
 * Create Date 2018/3/29 16:19
 * Describe 截圖工具
 * Version 1.0
 */

//開啓截圖
var psnode;//截圖節點
function startPrintps(node){
	psnode = node;
	if($("#psbg").length > 0){
		$("#psbg").css("display", "block");
	}else{
		//建立截圖面板並添加到body節點最後面
		var printpsPanel = '<div id="psbg"><div id="printrange"><div id="printfull"><div id="printcontent"></div><ul id="printbtn"><li><a onclick="closeps(event)">關閉</a></li><li style="display: none;"><a id="downloadps" onclick="closeps(event)">下載圖片</a></li><li><a onclick="resetps(event)">重置</a></li><li><a onclick="completeps(event)">完成</a></li></ul></div></div></div>';
		$(document.body).append(printpsPanel);
		//賦值樣式
		var w = $(window).width();
		var h = $(window).height();
		$("#psbg").attr("style", "margin:0;padding:0;z-index: 19950529;display: block;width: "+(w-4)+"px;height: "+(h-4)+"px;background: transparent;overflow: hidden;position: absolute;top: 0px;left: 0px;border: 2px solid #0066FF;");
		$("#psbg #printrange").attr("style", "margin:0;padding:0;z-index: 19950529;width: 0px;height: 0px;box-shadow: rgba(59,59,59,0.5) 0 0 0 2018px;display: inline-block;position: absolute;left: 30%;top: 30%;cursor: move;border: 1px solid #CC0000;");
		$("#psbg #printfull").attr("style", "margin:0;padding:0;width: 100%;height: 100%;position: relative;");
		$("#psbg #printcontent").attr("style", "margin:0;padding:0;width: 100%;height: 100%;position: absolute;left: 0px;top: 0px;");
		$("#psbg #printbtn").attr("style", "margin:0;padding:0;display: none;z-index: 1004;font-size: 14px;position: absolute;top: 0px;left: 0px;background-color: #0066FF;");
		$("#psbg #printbtn li").attr("style", "margin:0;padding:0;display: block;float: left;padding:5px;width: 32px;");
		$("#psbg #printbtn li:nth-child(2)").css("display", "none");
		$("#psbg #printbtn li:nth-child(2)").css("width", "58px");
		$("#psbg #printbtn li a").attr("style", "margin:0;padding:0;cursor: pointer;color: #FFF;text-decoration: none;");
	}
	pointToRecDrag(document.getElementById("printrange"));//註冊截圖事件
}
//完成截圖
function completeps(e){
	isCanDrag = false;//禁止拖拽
	e.stopPropagation();//阻止冒泡
	removeSetNodeEvent(document.getElementById("printrange"), 'onmousedown', drag);//註銷事件
	//生成圖片
	var prleft = $("#printrange").css("left");
	var prtop = $("#printrange").css("top");
	var startx = prleft.substring(0, prleft.length-2);
	var starty = prtop.substring(0, prtop.length-2);
	var imgw = $("#printrange").width();
	var imgh = $("#printrange").height();
	convertTHtml2Canvas(startx, starty, imgw, imgh);
	//顯示按鈕				
	$.each($("#printbtn li"), function(index, obj){
		$(obj).css("display", "none");
	});
	$("#printbtn li:first-child").css("display", "block");
	$("#printbtn li:nth-child(2)").css("display", "block");
	$("#printbtn").css("left", ($("#printrange").width()-110) + "px");
}
//關閉截圖
function closeps(e){
	isCanDrag = true;//容許拖拽
	e.stopPropagation();//阻止冒泡
	removeSetNodeEvent(document.getElementById("printrange"), 'onmousedown', drag);//註銷事件
	$("#printbtn").css("display", "none");
	//顯示按鈕				
	$.each($("#printbtn li"), function(index, obj){
		$(obj).css("display", "block");
	});
	$("#printbtn li:nth-child(2)").css("display", "none");
	$("#printbtn").css("left", ($("#printrange").width()-120) + "px");
	$("#printrange").css("width", "0px");
	$("#printrange").css("height", "0px");
	//還原背景
	$("#printcontent").css("background", "none");
	$("#psbg").css("background", "none");
	$("#psbg").css("display", "none");
}
//重置
function resetps(e){
	isCanDrag = true;//容許拖拽
	e.stopPropagation();//阻止冒泡
	removeSetNodeEvent(document.getElementById("printrange"), 'onmousedown', drag);//註銷事件
	$("#printbtn").css("display", "none");
	//顯示按鈕				
	$.each($("#printbtn li"), function(index, obj){
		$(obj).css("display", "block");
	});
	$("#printbtn li:nth-child(2)").css("display", "none");
	$("#printbtn").css("left", ($("#printrange").width()-120) + "px");
	$("#printrange").css("width", "0px");
	$("#printrange").css("height", "0px");
	//還原背景
	$("#printcontent").css("background", "none");
	$("#psbg").css("background", "none");
	//再從新註冊事件
	pointToRecDrag(document.getElementById("printrange"));
}
//Html轉換Canvas
function convertTHtml2Canvas(startx, starty, imgw, imgh) { 
	$("#psbg").css("display", "none");
	html2canvas(psnode, { allowTaint: true, taintTest: true }).then(function(canvas) {
    var img = convertTCanvasToImage(canvas);//轉換canvas獲得img·這時img是$("#divpic")範圍的
    $("#psbg").css("background", "url(" + img.src + ") no-repeat");
    $("#psbg").css("background-position", "-2px -2px");
    //img加載時···截取特定部分
    img.onload = function() {
    	$("#psbg").css("display", "block");
	    img.onload = null;
	    canvas = convertTImageToCanvas(img, Number(startx)+3, Number(starty)+3, imgw, imgh);//選定範圍從新繪製canvas
    	img = convertTCanvasToImage(canvas);//canvas再轉換img···截取到特定部分的圖片
    	var imgsrc = img.src;//獲取img的src
    	$("#printcontent").css("background", "url(" + imgsrc + ") no-repeat");
    	$("#printcontent").css("background-position", "0px 0px");
    	//下載圖片
			$('#downloadps').attr('href', imgsrc); //設置路徑
			$('#downloadps').attr('download', '截圖.png'); //設置下載圖片名稱
    }
  });
}
//canvas轉換圖片,返回圖片
function convertTCanvasToImage(canvas) {
	var image = new Image();
	image.src = canvas.toDataURL("image/png", 0.1);
	return image;
}
//圖片轉換canvas,返回canvas
function convertTImageToCanvas(image, startX, startY, width, height) {
	var canvas = document.createElement("canvas");
	canvas.width = width;
	canvas.height = height;
	canvas.getContext("2d").drawImage(image, startX, startY, width, height, 0, 0, width, height);
	return canvas;
}
//拉框截圖方法·jQuery
function pointToRecDrag(dragger){
	$("#psbg").on("mousedown", function(event){
		var w = $(window).width();
		var h = $(window).height();
		var clickX = event.pageX;
		var clickY = event.pageY;
		$(dragger).width("0px");
		$(dragger).height("0px");
		var draggerw = $(dragger).width();
		var draggerh = $(dragger).height();
		$(dragger).css("left", clickX + "px");
		$(dragger).css("top", clickY + "px");
		$("#psbg").on("mousemove", function(e){
			var mouseX = e.pageX;
			var mouseY = e.pageY;
			var difw = mouseX - clickX;//鼠標移動像素大小
			var difh = mouseY - clickY;
			if(difw<0 && difh<0){
				//向左上截圖
				$(dragger).css("left", (clickX+difw) + "px");
				$(dragger).css("top", (clickY+difh) + "px");
			}else if(difw>0 && difh<0){
				//向右上截圖
				$(dragger).css("top", (clickY+difh) + "px");
			}else if(difw<0 && difh>0){
				//向左下截圖
				$(dragger).css("left", (clickX+difw) + "px");
			}else{
				//向右下截圖
				$(dragger).css("left", clickX + "px");
				$(dragger).css("top", clickY + "px");
			}
			difw = Math.abs(difw); //取絕對值
			difh = Math.abs(difh);
			$(dragger).width(draggerw + difw + "px");
			$(dragger).height(draggerh + difh + "px");
		});
		$("#psbg").on("mouseup", function(ev){
			var mouseX = ev.pageX;
			var mouseY = ev.pageY;
			var difw = mouseX - clickX;//鼠標移動像素大小
			var difh = mouseY - clickY;
			//具體經過canvas截取img,直接賦值給dragger,而後就能夠下載保存
			if(difw<0 && difh<0){
				//按鈕位置
				$("#printbtn").css("left", ($(dragger).width()-127) + "px");
				$("#printbtn").css("top", ($(dragger).height()+1) + "px");
				if((mouseY + 4 + 28) > h){
					$("#printbtn").css("top", ($(dragger).height()-28) + "px");
				}
			}else if(difw>0 && difh<0){
				//按鈕位置
				$("#printbtn").css("left", ($(dragger).width()-127) + "px");
				$("#printbtn").css("top", ($(dragger).height()+1) + "px");
				if((mouseY + 4 + 28) > h){
					$("#printbtn").css("top", ($(dragger).height()-28) + "px");
				}
			}else if(difw<0 && difh>0){
				//按鈕位置
				$("#printbtn").css("left", ($(dragger).width()-127) + "px");
				$("#printbtn").css("top", ($(dragger).height()+1) + "px");
				if((mouseY + 4 + 28) > h){
					$("#printbtn").css("top", ($(dragger).height()-28) + "px");
				}
			}else{
				//按鈕位置
				$("#printbtn").css("left", ($(dragger).width()-127) + "px");
				$("#printbtn").css("top", ($(dragger).height()+1) + "px");
				if((mouseY + 4 + 28) > h){
					$("#printbtn").css("top", ($(dragger).height()-28) + "px");
				}
			}
			$("#printbtn").css("display", "block");//按鈕
			//移除截圖事件
			$("#psbg").off("mousemove");
			$("#psbg").off("mousedown");
			$("#psbg").off("mouseup");
			//註冊拖框事件
			dragNodeElement(document.getElementById("printrange"));
		});
	});
}
//拖拽方法·js
var isCanDrag = true;//是否容許拖拉
var drag; //拖拽對象
function dragNodeElement(dragger) {
	if(isCanDrag){
		var w = document.documentElement.clientWidth || document.body.clientWidth;
		var h = document.documentElement.clientHeight || document.body.clientHeight;
		drag = bindTNodeEvent(dragger, 'onmousedown', function(e) {
			var printrangew = $("#printrange").width();
			var printrangeh = $("#printrange").height();
			e = e || event;
			var mouseX = e.clientX || e.pageX;
			var mouseY = e.clientY || e.pageY;
			var objStyle = dragger.currentStyle || window.getComputedStyle(dragger, null);
			var objX = parseInt(objStyle.left) || 0;
			var objY = parseInt(objStyle.top) || 0;
			var limitX = mouseX - objX;
			var limitY = mouseY - objY;
			if(!dragger.onDrag) {
				dragger.onDrag = bindTNodeEvent(document, 'onmousemove', function(e) {
					e = e || event;
					dragger.style.left = ((e.clientX || e.pageX) - limitX) + 'px';
					dragger.style.top = ((e.clientY || e.pageY) - limitY) + 'px';
					if(h - ((e.clientY || e.pageY) - limitY + printrangeh + 6) < 28){
						$("#printbtn").css("top", ($(dragger).height()-28) + "px");
					}else{
						$("#printbtn").css("top", ($(dragger).height()+1) + "px");
					}
					if(parseInt(dragger.style.left) <= 2) {
						dragger.style.left = 2 + "px";
					}
					if(parseInt(dragger.style.left) >= (w - printrangew - 6)) {
						dragger.style.left = (w - printrangew - 6) + "px";
					}
					if(parseInt(dragger.style.top) >= (h - printrangeh - 6)) {
						dragger.style.top = (h - printrangeh - 6) + "px";
					}
					if(parseInt(dragger.style.top) <= 2) {
						dragger.style.top = 2 + "px";
					}
				});
				dragger.onDragEnd = bindTNodeEvent(document, 'onmouseup', function() {
					removeSetNodeEvent(document, 'onmousemove', dragger.onDrag);
					removeSetNodeEvent(document, 'onmouseup', dragger.onDragEnd);
					try {
						delete dragger.onDrag;
						delete dragger.onDragEnd;
					} catch(e) {
						dragger.removeAttribute('onDrag');
						dragger.removeAttribute('onDragEnd');
					}
				});
			}
		});
	}
}
//添加事件
function bindTNodeEvent(node, eventType, callback) {
	if(node.attachEvent) {
		if(eventType.indexOf('on')) { eventType = 'on' + eventType }
		node.attachEvent(eventType, callback);
	} else {
		if(!eventType.indexOf('on')) {
			eventType = eventType.substring(2, eventType.length);
		}
		node.addEventListener(eventType, callback, false);
	}
	return callback;
}
//移除事件
function removeSetNodeEvent(node, eventType, callback) {
	if(node.detachEvent) {
		if(eventType.indexOf('on')) { eventType = 'on' + eventType }
		node.detachEvent(eventType, callback);
	} else {
		if(!eventType.indexOf('on')) {
			eventType = eventType.substring(2, eventType.length);
		}
		node.removeEventListener(eventType, callback, false);
	}
}

 

三、簡單使用demo:SnippingTool.htmlcanvas

 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>截圖</title>
		<script src="js/jquery.2.1.4.min.js"></script>
		<script src="js/html2canvas.js"></script>
		<script src="js/SnippingTool.js"></script>
		<!-- box-shadow:http://www.w3school.com.cn/cssref/pr_box-shadow.asp -->
	</head>
	<body>
		<div id="container">
			<div id="content" style="margin: 10px;">
				<img src="img/grass.png" width="1000px" height="400px"/>
				<p>What do you do every day?What have you gained?</p>
			</div>
		</div>
		<button onclick="start()">截圖</button>
	</body>
	
	<script type="text/javascript">
		function start(){
			//使用方法
			startPrintps($("body"));//截圖,參數body對象
		}
	</script>
</html>

 

 

 

以上就代碼了,就這樣啦,僅供參考學習。。。app

 

源代碼下載地址:工具

點擊下載代碼學習

相關文章
相關標籤/搜索