天天看點

canvas生成圖檔并下載下傳圖檔或者pdfcanvas生成圖檔并下載下傳圖檔或者pdf

canvas生成圖檔并下載下傳圖檔或者pdf

如題 , 用的是html2canvas和jspdf來實作的

html2canvas截圖是截取可視區域之内的

代碼需要放到伺服器上運作, 不然toDataURL()會顯示跨域錯誤

<script type="text/javascript" src="js/jquery1.9.1.min.js"></script>
<script src="js/html2canvas.min.js" type="text/javascript"></script>
<script src="js/jspdf.min.js" type="text/javascript"></script>
    
$('#renderPdf').on('click', function (e) {
	var w = $('#zhengshu').width()
	var h = $('#zhengshu').height()
	var canvas = document.createElement("canvas")
	canvas.width = w * 2;
	canvas.height = h * 2;
	canvas.style.width = w + "px"
	canvas.style.height = h + "px"
	var context = canvas.getContext("2d"); //然後将畫布縮放,将圖像放大兩倍畫到畫布上
	context.scale(2, 2)
	html2canvas($('#zhengshu'), {
		canvas: canvas,
		useCORS: true, //使用跨域
		onrendered: function (canvas) {
			var url = canvas.toDataURL('image/png', 1.0);
			//之前本地用Base64下載下傳會顯示網絡錯誤, 然後用Blob進行轉換
   			canvas.toBlob(function (blob) {
				href = URL.createObjectURL(blob)
				//html5 download屬性,隻有chrome, firefox可以使用
				var $a = $('<a></a>').attr('href', href).attr('download', 'download.png').appendTo('body')
				$a[0].click()
				$a.remove()
				})
			//下載下傳為pdf格式	但是下載下傳為pdf會模糊,還沒有解決
			//方向預設豎直 'l'代表橫闆,尺寸ponits,格式 b5[498.90, 708.66] 
			//var pdf = new jsPDF('l') 
			//addImage後兩個參數控制添加圖檔的尺寸
			//pdf.addImage(url, 'png', 0, 0, 298, 210) 
			//pdf.save('證書.pdf')
			}
		})
	 e.preventDefault()
})