作用
html2canvas可以通過純JS對瀏覽器端經行截屏,但截圖的精確度還有待提高,部分css不可識別,所以在canvas中不能完美呈現原畫面樣式
/*多行溢出省略就不行,只能超出隱藏了*/ .book_inf{ position: relative; overflow : hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
支持的瀏覽器
Firefox 3.5+
Google Chrome
Opera 12+
IE9+
Safari 6+
基本語法
/*參數:* #screenshots 所需要截圖的元素id,截圖后要執行的函數,* backgroundColor 配置項背景色* canvas為截圖后返回的最后一個canvasfunction screenshotsImg(){ html2canvas(document.querySelector( #screenshots ),{ backgroundColor: transparent ,// 設置背景透明 }).then(canvas = { canvasTurnImg(canvas) //保存的圖片格式轉換方法 }
可用配置項
參數名稱類型默認值描述allowTaintbooleanfalseWhether to allow cross-origin images to taint the canvas---允許跨域backgroundstring#fffCanvas background color, if none is specified in DOM. Set undefined for transparent---canvas的背景顏色,如果沒有設定默認白色此處被坑,我改為backgroundColor可用heightnumbernullDefine the heigt of the canvas in pixels. If null, renders with full height of the window.---canvas高度設定letterRenderingbooleanfalseWhether to render each letter seperately. Necessary if letter-spacing is used.---在設置了字間距的時候有用loggingbooleanfalseWhether to log events in the console.---在console.log()中輸出信息proxystringundefinedUrl to the proxy which is to be used for loading cross-origin images. If left empty, cross-origin images won t be loaded.---代理地址taintTestbooleantrueWhether to test each image if it taints the canvas before drawing them---是否在渲染前測試圖片timeoutnumber0Timeout for loading images, in milliseconds. Setting it to 0 will result in no timeout.---圖片加載延遲,默認延遲為0,單位毫秒widthnumbernullDefine the width of the canvas in pixels. If null, renders with full width of the window.---canvas寬度useCORSbooleanfalseWhether to attempt to load cross-origin images as CORS served, before reverting back to proxy--跨域代理設置圖片格式
1、從canvas中直接提取圖片元數據
// 圖片導出為 png 格式 var type = png var imgData = canvas.toDataURL(type);
2、將mime-type改為image/octet-stream,強制讓瀏覽器直接download
/** * 獲取mimeType * @param {String} type the old mime-type * @return the new mime-typevar _fixType = function(type) { type = type.toLowerCase().replace(/jpg/i, jpeg var r = type.match(/png|jpeg|bmp|gif/)[0]; return image/ + r;// 加工image data,替換mime typeimgData = imgData.replace(_fixType(type), image/octet-stream
3、圖片download到本地
/** * 在本地進行文件保存 * @param {String} data 要保存到本地的圖片數據 * @param {String} filename 文件名var saveFile = function(data, filename){ var save_link = document.createElementNS( http://www.w3.org/1999/xhtml , a save_link.href = data; save_link.download = filename; var event = document.createEvent( MouseEvents event.initMouseEvent( click , true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); save_link.dispatchEvent(event);// 下載后的文件名var filename = baidufe_ + (new Date()).getTime() + . + type;// downloadsaveFile(imgData,filename);
相關推薦:
html5瀏覽器截圖的示例
以上就是html2 canvas實現瀏覽器截圖的詳細內容,html教程
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答