用途
我们现在写的h5页面基本上都是在微信中使用较多,为了扩大影响范围经常会出现需要分享到好友或者朋友圈.
之前的实现都是将网页的地址分享出去,携带相关的分享图片,标题,大致内容.这次尝试一下用js实现截屏图片保存.
html2canvas
html2canvas官网
这次使用的是html2canvas去达到截屏的效果,非常简单好用.
下载与使用
1.下载
npm
npm install --save html2canvas
yan
yarn add html2canvas
2.使用
直接引入文件使用就可以了,官方介绍也很简单,直接码代码
html2canvas examplefunction takeScreenshot() {
html2canvas(document.body).then(function(canvas) {
document.body.appendChild(canvas);
var url = canvas.toDataURL();
console.log(url);
});
}
//不用往后拖了,为了方便看效果,放的是base64转码后的图片地址,所以很长....
可使用参数
参数名称
默认值
描述
async
true
Whether to parse and render the element asynchronously-是否异步解析和渲染元素
allowTaint
false
Whether to allow cross-origin images to taint the canvas-是否允许跨域数据污染'被污染'的canvas
backgroundColor
#ffffff
Canvas background color, if none is specified in DOM. Set null for transparent -画布的背景色,没有设置的话默认为null,背景色为透明
canvas
null
Existing canvas element to use as a base for drawing on-使用已存在的画布上进行绘制
foreignObjectRendering
false
Whether to use ForeignObject rendering if the browser supports it -是否在浏览器支持的情况下使用ForeignObject模式渲染图片
imageTimeout
15000
Timeout for loading an image (in milliseconds). Set to 0 to disable timeout.-超时设置(单位为毫秒),设为0时禁止超时
ignoreElements
(element) => false
Predicate function which removes the matching elements from the render. - 在渲染的时候移除匹配元素
logging
true
Enable logging for debug purposes -启用日志记录进行调试
onclone
null
Callback function which is called when the Document has been cloned for rendering, can be used to modify the contents that will be rendered without affecting the original source document. -在克隆文档进行渲染时调用的回调函数,可用于修改在不影响原始文档的情况下呈现的内容。
proxy
null
Url to the proxy which is to be used for loading cross-origin images. If left empty, cross-origin images won't be loaded.用于加载跨域图像。如果留空,则不会加载跨跨域图像
removeContainer
true
Whether to cleanup the cloned DOM elements html2canvas creates temporarily-是否需要清除html2canvas克隆时临时创造的dom元素
scale
window.devicePixelRatio
The scale to use for rendering. Defaults to the browsers device pixel ratio. -渲染时使用,默认渲染时使用浏览器自带的像素比
useCORS
false
Whether to attempt to load images from a server using CORS-是否尝试使用CORS从服务器加载图像
width
Element width
The width of the canvas-画布的宽度
height
Element height
The height of the canvas -画布的高度
x
Element x-offset
Crop canvas x-coordinate-裁剪时画布横坐标
y
Element y-offset
Crop canvas y-coordinate-裁剪时画布的纵坐标
scrollX
Element scrollX
The x-scroll position to used when rendering element, (for example if the Element uses position: fixed )-渲染元素时使用的x滚动位置
scrollY
Element scrollY
The y-scroll position to used when rendering element, (for example if the Element uses position: fixed )-渲染元素时使用的y滚动位置
windowWidth
Window.innerWidth
Window width to use when rendering Element , which may affect things like Media queries-渲染时使用的窗口宽度
windowHeight
Window.innerHeight
Window height to use when rendering Element , which may affect things like Media queries-渲染时使用的窗口高度