使用JavaScript将页面导出为图片

昨天心血来潮,突然想将我们组开发的网站上的“导出Excel”功能做一点拓展,于是就想能不能直接将网页表格导出为图片!

在我的不懈搜索后(搜索过程中绝大部分博客上的博文要么相互抄袭要么没什么屁用),终于得到了“canvas2image.js”这个神奇的JavaScript脚本,具体使用办法见如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<!doctype html>
<html>
<script src="canvas2image.js"></script>
<body>
<canvas id="cvs"></canvas>
<button id="save">save</button>
<script>
var canvas, ctx, bMouseIsDown = false, iLastX, iLastY,
$save, $imgs,
$convert, $imgW, $imgH,
$sel;
function init (){
canvas = document.getElementById('cvs');
ctx = canvas.getContext('2d');
$save = document.getElementById('save');
$convert = document.getElementById('convert');
$sel = "png";
$imgs = document.getElementById('imgs');
$imgW = 1980;
$imgH = 2000;
bind();
draw();
}
function bind () {
canvas.onmousedown = function(e) {
bMouseIsDown = true;
iLastX = e.clientX - canvas.offsetLeft + (window.pageXOffset||document.body.scrollLeft||document.documentElement.scrollLeft);
iLastY = e.clientY - canvas.offsetTop + (window.pageYOffset||document.body.scrollTop||document.documentElement.scrollTop);
}
canvas.onmouseup = function() {
bMouseIsDown = false;
iLastX = -1;
iLastY = -1;
}
canvas.onmousemove = function(e) {
if (bMouseIsDown) {
var iX = e.clientX - canvas.offsetLeft + (window.pageXOffset||document.body.scrollLeft||document.documentElement.scrollLeft);
var iY = e.clientY - canvas.offsetTop + (window.pageYOffset||document.body.scrollTop||document.documentElement.scrollTop);
ctx.moveTo(iLastX, iLastY);
ctx.lineTo(iX, iY);
ctx.stroke();
iLastX = iX;
iLastY = iY;
}
};
$save.onclick = function (e) {
var type = $sel.value,
w = $imgW.value,
h = $imgH.value;
Canvas2Image.saveAsImage(canvas, w, h, type);
}
}
onload = init;
</script>
</body>
</html>



本文链接: http://home.meng.uno/articles/f03eda59/ 欢迎转载!

© 2018.02.08 - 2020.10.14 Mengmeng Kuang  保留所有权利!

UV : | PV :

:D 获取中...

Creative Commons License