## **html2canvas html截图插件图片放大清晰度解决方案,支持任意放大倍数,解决原插件图片偏移问题** {#articleHeader0}
Author:youzebin \(2016.12.6\)
插件下载地址:[https://github.com/niklasvh/h...](https://github.com/niklasvh/html2canvas)
1.首先引入html2canvas.js html2canvas 0.5.0-beta4 最新版即可
必要步骤1:修改插件的源码: (修改的地方有两处)
#### 1. 代码第 999 行 renderWindow 的方法中 修改判断条件 增加一个options.scale存在的条件:
源码:
```
if (options.type === "view") {
canvas = crop(renderer.canvas, {width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0});
} else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement || options.canvas != null) {
canvas = renderer.canvas;
} else {
canvas = crop(renderer.canvas, {width: options.width != null ? options.width : bounds.width, height: options.height != null ? options.height : bounds.height, top: bounds.top, left: bounds.left, x: 0, y: 0});
}
```
改为:
```
if (options.type === "view") {
canvas = crop(renderer.canvas, {width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0});
} else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement) {
canvas = renderer.canvas;
}else if(options.scale && options.canvas !=null){
log("放大canvas",options.canvas);
var scale = options.scale || 1;
canvas = crop(renderer.canvas, {width: bounds.width * scale, height:bounds.height * scale, top: bounds.top *scale, left: bounds.left *scale, x: 0, y: 0});
}
else {
canvas = crop(renderer.canvas, {width: options.width != null ? options.width : bounds.width, height: options.height != null ? options.height : bounds.height, top: bounds.top, left: bounds.left, x: 0, y: 0});
}
```
#### 2. 代码第 943 行 html2canvas 的方法中 修改width,height:
源码:
```
return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function(canvas) {
if (typeof(options.onrendered) === "function") {
log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
options.onrendered(canvas);
}
return canvas;
});
```
改为:
```
width = options.width != null ? options.width : node.ownerDocument.defaultView.innerWidth;
height = options.height != null ? options.height : node.ownerDocument.defaultView.innerHeight;
return renderDocument(node.ownerDocument, options, width, height, index).then(function(canvas) {
if (typeof(options.onrendered) === "function") {
log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
options.onrendered(canvas);
}
return canvas;
});
```
2.使用方式
```
var shareContent = document.getElementById("shareContent");//需要截图的包裹的(原生的)DOM 对象
var width = shareContent.offsetWidth; //获取dom 宽度
var height = shareContent.offsetHeight; //获取dom 高度
var canvas = document.createElement("canvas"); //创建一个canvas节点
var scale = 2; //定义任意放大倍数 支持小数
canvas.width = width * scale; //定义canvas 宽度 * 缩放
canvas.height = height * scale; //定义canvas高度 *缩放
canvas.getContext("2d").scale(scale,scale); //获取context,设置scale
var opts = {
scale:scale, // 添加的scale 参数
canvas:canvas, //自定义 canvas
logging: true, //日志开关
width:width, //dom 原始宽度
height:height //dom 原始高度
};
html2canvas(shareContent, opts).then(function (canvas) {
//如果想要生成图片 引入canvas2Image.js 下载地址:
//https://github.com/hongru/canvas2image/blob/master/canvas2image.js
var img = Canvas2Image.convertToImage(canvas, canvas.width, canvas.height);
console.log(img);
});
```
## **2017.1.7 优化插件使用的方式,并附上demo (插件的改动还是按照上面的操作流程)** {#articleHeader1}
(不好意思各位,最近发现上面插件的使用方式上存在截图不完整的bug,
很多人在插件的使用上存在各种各样的问题。所以决定完善这篇文章的内容)
以下我总结了一些注意事项,在代码中注释了,仅供参考。
付:完整使用的demo ,如下:
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<title>html2Canvas demo</title>
<script>
document.documentElement.style.fontSize = window.screen.width / 7.5 + 'px';
</script>
<style>
body,
html,
div,
p,
ul,
li,
a,
img,
span,
button,
header,
footer,
section {
padding: 0;
margin: 0;
}
*, :before, :after {
-webkit-tap-highlight-color: transparent;
-webkit-user-select: none;
outline: none;
box-sizing: border-box;
-webkit-box-sizing: border-box;
}
::-webkit-scrollbar {
width: 0;
opacity: 0;
}
button{
font-family: simsun,"microsoft yahei", arial, "Helvetica Neue", Helvetica, STHeiTi, sans-serif;
}
body {
font-family: "microsoft yahei", arial, "Helvetica Neue", Helvetica, STHeiTi, sans-serif;
color: #000;
background-color: #f5f5f5;
-webkit-overflow-scrolling: touch;
}
.share-container {
padding-top: 0.72rem;
width: 2.35rem;
margin: 0 auto;
}
.share-content {
padding-top: 0.72rem;
height:3rem;
background-color: blue;
border-radius: 5px;
width: 100%;
}
.text{
font-size: 0.36rem;
color: #f2f2f2;
}
.btn-share {
width: 64%;
height: 0.89rem;
background-color: #3baaff;
border-radius: 0.89rem;
border: 1px solid #3baaff;
color: white;
font-size: 0.36rem;
margin: 0.75rem 0 0.67rem;
}
.btn-share:active{
background-color: #1b96c8;
}
</style>
</head>
<body>
<section class="main-container">
<header class="share-container" id="shareContainer">
<div class="share-content" id="shareContent">
<div class="text">
<p>文字,图片等内容</p>
</div>
</div>
</header>
<footer class="footer-center">
<button class="btn-share" id="btnShare">截 图</button>
</footer>
</section>
<script src="static/js/html2canvas.js"></script>
<script>
//定义查找元素方法
function $(selector) {
return document.querySelector(selector);
}
var main = {
init:function(){
main.setListener();
},
//设置监听事件
setListener:function(){
var btnShare = document.getElementById("btnShare");
btnShare.onclick = function(){
main.html2Canvas();
}
},
//获取像素密度
getPixelRatio:function(context){
var backingStore = context.backingStorePixelRatio ||
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
return (window.devicePixelRatio || 1) / backingStore;
},
//绘制dom 元素,生成截图canvas
html2Canvas: function () {
var shareContent = $("#shareContent");// 需要绘制的部分的 (原生)dom 对象 ,注意容器的宽度不要使用百分比,使用固定宽度,避免缩放问题
var width = shareContent.offsetWidth; // 获取(原生)dom 宽度
var height = shareContent.offsetHeight; // 获取(原生)dom 高
var offsetTop = shareContent.offsetTop; //元素距离顶部的偏移量
var canvas = document.createElement('canvas'); //创建canvas 对象
var context = canvas.getContext('2d');
var scaleBy = main.getPixelRatio(context); //获取像素密度的方法 (也可以采用自定义缩放比例)
canvas.width = width * scaleBy; //这里 由于绘制的dom 为固定宽度,居中,所以没有偏移
canvas.height = (height + offsetTop) * scaleBy; // 注意高度问题,由于顶部有个距离所以要加上顶部的距离,解决图像高度偏移问题
context.scale(scaleBy, scaleBy);
var opts = {
allowTaint:true,//允许加载跨域的图片
tainttest:true, //检测每张图片都已经加载完成
scale:scaleBy, // 添加的scale 参数
canvas:canvas, //自定义 canvas
logging: true, //日志开关,发布的时候记得改成false
width:width, //dom 原始宽度
height:height //dom 原始高度
};
html2canvas(shareContent, opts).then(function (canvas) {
console.log("html2canvas");
var body = document.getElementsByTagName("body");
body[0].appendChild(canvas);
});
}
};
//最后运行代码
main.init();
</script>
</body>
</html>
```
## 运行上面的demo 前有以下**注意点**: {#articleHeader2}
1. 前面的内容没看过,没下载过html2canvas.js 没按照插件改过说明操作的先改好再说
2. 注意元素的样式的使用:
外层元素width 不能使用百分比 ,避免导致图片与文字间缩放比例问题
```
错误使用方式如
.container {
width:50%;
margin: 0 auto;
}
```
需要改成如:
```
.container {
width:300px;
margin: 0 auto;
}
```
附上react导出pdf demo,经测试放大1.8较清晰
```
var shareContent = document.getElementById("table2_1");//需要截图的包裹的(原生的)DOM 对象
var width = shareContent.offsetWidth; //获取dom 宽度
var height = shareContent.offsetHeight; //获取dom 高度
var canvas = document.createElement("canvas"); //创建一个canvas节点
var scale = 1.5; //定义任意放大倍数 支持小数
canvas.width = width * scale; //定义canvas 宽度 * 缩放
canvas.height = height * scale; //定义canvas高度 *缩放
canvas.getContext("2d").scale(scale, scale); //获取context,设置scale
var opts = {
scale: scale, // 添加的scale 参数
canvas: canvas, //自定义 canvas
logging: true, //日志开关
width: width, //dom 原始宽度
height: height //dom 原始高度
};
html2canvas(shareContent, opts).then((canvas) => {
//返回图片URL,参数:图片格式和清晰度(0-1)
var pageData = canvas.toDataURL('image/jpeg', 1.0);
//方向默认竖直,尺寸ponits, 按照图片大小进行输出
var pdf = new jsPDF('l', 'px', [canvas.width, canvas.height]);
//需要dataUrl格式
pdf.addImage(pageData, 'JPEG', 0, 0, canvas.width, canvas.height);
pdf.save('1-2.pdf');
});
```
- 首页
- pm2
- pm2
- pm2 离线安装
- pm2 使用指南
- node
- 正则
- web
- webpack
- 配置
- 优化代码体积
- plugin-proposal-decorators
- webpack 打包原理解析
- babel presets配置 babel7
- 配置路径别名
- 去除开发中的警告信息
- css
- 滚动条
- input自动填充背景色
- 颜色渐变
- scss
- 网页定制光标
- 超出文本显示省略号。。。
- calc兼容性写法
- box-sizing
- clip-path
- 苹果手机页面滑动卡顿
- 字体间距根据父级宽度自适应
- 纯css动态效果
- 清除浮动的三种方法
- 按钮增加闪烁效果
- 字体渐变
- react
- mobx
- 路由
- antd 表格在safari上卡顿
- 项目初始化
- react-antd-mobx-momnet
- 显示字符串中的标签
- antd Select 在搜索精准度
- 路由切换动态过渡效果
- css中图片打包后的路径出错
- antd upload 无法及时更新state
- antd DatePicker设置中文失败
- antd-pro 添加登录页面报错
- new Array创建新数组数据指向相同
- react 页面刷新渲染两次
- useEffect
- Hooks 闭包解决方案
- hooks 方法封装
- Plugin "react" was conflicted between "package.json » eslint-config-react-app
- javascript
- canvas
- 多张图片合成一张
- 排序
- js比较符号==、===
- 运动函数封装(简易、通用)
- 导出表格(excel )
- react使用demo
- xlsx导出excel
- js获取屏幕高度宽度
- toFixed 函数修改
- 获取cookie,url参数
- 奇怪的错误问题
- copy(深拷贝 浅拷贝)
- 导出pdf
- 解决图片失真
- 判断字符串长度(带中文)
- js中 文件、图片二进制和base64的互转
- 读取深度嵌套的json数据
- 手动实现Promise.all
- cookie 删除
- webpack 打包过后的文件报错 regeneratorRuntime is not defined
- 防抖与节流
- react hooks 中使用防抖节流
- 图片懒加载
- 重排和重绘
- 修复部分无法JASON.parse的数据
- react-native
- android-studio 打开调试工具
- 适配全面屏
- node
- 服务端 node + nginx 反向代理
- 生成文件夹目录列表
- mogodb常用操作
- 发布npm包
- cli工具
- 上传文件
- nodejs使用crypto进行加密/解密操作
- mongodb 加入验证之后连接失败
- nextjs使用问题
- node转发http请求
- mongodb 导入导出 备份
- node-sass 安装问题、安装失败等
- npm yarn 安装依赖太慢
- puppeteer 安装问题 centos
- mongoose
- 其他
- 禁止浏览器缓存
- chrome平滑滚动
- pdf预览
- 问题整理
- 资料
- 小程序
- fetch
- cookie 设置跨域资源共享
- taro 小程序
- taro request
- 设置npm镜像
- esbuild the service is no longer running
- 离线地图
- uniapp 转 vue-cli
- 工具
- Excel表格密码保护的解除方法
- vscode(插件)
- vscode 常用代码片段
- vscode 开启tab补全代码
- mac 百度网盘破解
- mysql 重置密码
- chrome 好用的扩展
- Mac/Linux/Windows通过命令调用浏览器打开某网页
- 小链接
- 数据库
- mongo
- sql文件导入
- join 用法
- sql 时间格式化 DATE_FORMAT
- 创建全文检索并分词查询
- 阿里云node-mysql 操作文档
- sql 时间查询
- mysql group查询结果合并为一行
- mysql 锁
- mysql count 同个字段多个结果合并到一行
- 解决Node.js mysql客户端不支持认证协议引发的“ER_NOT_SUPPORTED_AUTH_MODE”问题
- mysql 根据经纬度计算距离
- PHP
- 文件读取
- 接收前端json数据
- 自定义排序
- session 写入失败无法保存
- php 上传大文件$_FILES为空
- base64转图片
- composer.phar 安装东西太慢 切换国内镜像
- laravel sql查询记录
- 解决: Please provide a valid cache path.
- thinkphp开启多应用
- 上传文件报错 Filename cannot be empty
- php curl 报错 curl: (35) SSL connect error
- App
- android未授权错误(Flutter)
- uniapp
- 服务端
- mongodb 定时备份
- mysql 错误
- nginx 转发网络请求
- midwayjs 使用egg-mysql
- https 无法访问
- egg 配置跨域
- 算法实现
- 排序
- 全排列
- 无重复字符的最长子串
- 反转单向链表
- 斐波那契数列
- 有效的括号
- GIT
- git克隆大文件
- 面试整理
- 前端整理
- 大厂高级前端面试题
- 三年大厂面试题
- 面试经验
- 头条it技术工程师
- 每日学习
- 常见的数据结构
- 面试地址汇总
- 练习汇总
- 前端八股文
- mac环境配置
- mac nginx重启报错
- mac 安装redis
- fis配置
- 切换php版本
- Mac OS X下的Oh-My-ZSH安装与配置
- mac 查看端口进程 停止进程
- mac 配置ssh 免密码登录服务器
- navigate 中文破解
- 删除启动台无效文件夹
- 删除顶部图标(卸载后的软件还存在)
- 修复mac 下安装全局依赖失效
- navicate 完美破解 内有下载地址
- nginx 报错 500 "/usr/local/var/run/nginx/client_body_temp/0000000004" failed (13: Permission denied)
- 安装PHP redis扩展
- 安装zsh后 nvm node命令失效
- python
- python 在vscode中编辑,格式化文件总是提示There is no Pip installer available in the selected environment.
- 杂项
- 膝盖修复
- 微信打开网页链接反应巨慢
- chrome 显示http/https完整连接
- doracms
- pdfjs 中文无法显示
- docker
- go
- 指针、指针地址* &
- 脚本
- 京东疯狂的joy脚本
- 2021京东炸年兽
- LINUX
