html2canvas和canvas2image将dom元素转化成图片

1.依赖的文件

<script src="html2canvas.js"></script>
<script src="canvas2image.js"></script>
<script src="jquery-1.9.0.min.js"></script>

html2canvas官网:
http://html2canvas.hertzen.com/?utm_source=caibaojian.com

js地址:http://html2canvas.hertzen.com/dist/html2canvas.js

canvas2image:

/**
 * covert canvas to image
 * and save the image file
 */

var Canvas2Image = function () {

	// check if support sth.
	var $support = function () {
		var canvas = document.createElement('canvas'),
			ctx = canvas.getContext('2d');

		return {
			canvas: !!ctx,
			imageData: !!ctx.getImageData,
			dataURL: !!canvas.toDataURL,
			btoa: !!window.btoa
		};
	}();

	var downloadMime = 'image/octet-stream';

	function scaleCanvas (canvas, width, height) {
		var w = canvas.width,
			h = canvas.height;
		if (width == undefined) {
			width = w;
		}
		if (height == undefined) {
			height = h;
		}

		var retCanvas = document.createElement('canvas');
		var retCtx = retCanvas.getContext('2d');
		retCanvas.width = width;
		retCanvas.height = height;
		retCtx.drawImage(canvas, 0, 0, w, h, 0, 0, width, height);
		return retCanvas;
	}

	function getDataURL (canvas, type, width, height) {
		canvas = scaleCanvas(canvas, width, height);
		return canvas.toDataURL(type);
	}

	function saveFile (strData) {
		document.location.href = strData;
	}

	function genImage(strData) {
		var img = document.createElement('img');
		img.src = strData;
		return img;
	}
	function fixType (type) {
		type = type.toLowerCase().replace(/jpg/i, 'jpeg');
		var r = type.match(/png|jpeg|bmp|gif/)[0];
		return 'image/' + r;
	}
	function encodeData (data) {
		if (!window.btoa) { throw 'btoa undefined' }
		var str = '';
		if (typeof data == 'string') {
			str = data;
		} else {
			for (var i = 0; i < data.length; i ++) {
				str += String.fromCharCode(data[i]);
			}
		}

		return btoa(str);
	}
	function getImageData (canvas) {
		var w = canvas.width,
			h = canvas.height;
		return canvas.getContext('2d').getImageData(0, 0, w, h);
	}
	function makeURI (strData, type) {
		return 'data:' + type + ';base64,' + strData;
	}


	/**
	 * create bitmap image
	 * 鎸夌収瑙勫垯鐢熸垚鍥剧墖鍝嶅簲澶村拰鍝嶅簲浣�
	 */
	var genBitmapImage = function (oData) {

		//
		// BITMAPFILEHEADER: http://msdn.microsoft.com/en-us/library/windows/desktop/dd183374(v=vs.85).aspx
		// BITMAPINFOHEADER: http://msdn.microsoft.com/en-us/library/dd183376.aspx
		//

		var biWidth  = oData.width;
		var biHeight	= oData.height;
		var biSizeImage = biWidth * biHeight * 3;
		var bfSize  = biSizeImage + 54; // total header size = 54 bytes

		//
		//  typedef struct tagBITMAPFILEHEADER {
		//  	WORD bfType;
		//  	DWORD bfSize;
		//  	WORD bfReserved1;
		//  	WORD bfReserved2;
		//  	DWORD bfOffBits;
		//  } BITMAPFILEHEADER;
		//
		var BITMAPFILEHEADER = [
			// WORD bfType -- The file type signature; must be "BM"
			0x42, 0x4D,
			// DWORD bfSize -- The size, in bytes, of the bitmap file
			bfSize & 0xff, bfSize >> 8 & 0xff, bfSize >> 16 & 0xff, bfSize >> 24 & 0xff,
			// WORD bfReserved1 -- Reserved; must be zero
			0, 0,
			// WORD bfReserved2 -- Reserved; must be zero
			0, 0,
			// DWORD bfOffBits -- The offset, in bytes, from the beginning of the BITMAPFILEHEADER structure to the bitmap bits.
			54, 0, 0, 0
		];

		//
		//  typedef struct tagBITMAPINFOHEADER {
		//  	DWORD biSize;
		//  	LONG  biWidth;
		//  	LONG  biHeight;
		//  	WORD  biPlanes;
		//  	WORD  biBitCount;
		//  	DWORD biCompression;
		//  	DWORD biSizeImage;
		//  	LONG  biXPelsPerMeter;
		//  	LONG  biYPelsPerMeter;
		//  	DWORD biClrUsed;
		//  	DWORD biClrImportant;
		//  } BITMAPINFOHEADER, *PBITMAPINFOHEADER;
		//
		var BITMAPINFOHEADER = [
			// DWORD biSize -- The number of bytes required by the structure
			40, 0, 0, 0,
			// LONG biWidth -- The width of the bitmap, in pixels
			biWidth & 0xff, biWidth >> 8 & 0xff, biWidth >> 16 & 0xff, biWidth >> 24 & 0xff,
			// LONG biHeight -- The height of the bitmap, in pixels
			biHeight & 0xff, biHeight >> 8  & 0xff, biHeight >> 16 & 0xff, biHeight >> 24 & 0xff,
			// WORD biPlanes -- The number of planes for the target device. This value must be set to 1
			1, 0,
			// WORD biBitCount -- The number of bits-per-pixel, 24 bits-per-pixel -- the bitmap
			// has a maximum of 2^24 colors (16777216, Truecolor)
			24, 0,
			// DWORD biCompression -- The type of compression, BI_RGB (code 0) -- uncompressed
			0, 0, 0, 0,
			// DWORD biSizeImage -- The size, in bytes, of the image. This may be set to zero for BI_RGB bitmaps
			biSizeImage & 0xff, biSizeImage >> 8 & 0xff, biSizeImage >> 16 & 0xff, biSizeImage >> 24 & 0xff,
			// LONG biXPelsPerMeter, unused
			0,0,0,0,
			// LONG biYPelsPerMeter, unused
			0,0,0,0,
			// DWORD biClrUsed, the number of color indexes of palette, unused
			0,0,0,0,
			// DWORD biClrImportant, unused
			0,0,0,0
		];

		var iPadding = (4 - ((biWidth * 3) % 4)) % 4;

		var aImgData = oData.data;

		var strPixelData = '';
		var biWidth4 = biWidth<<2;
		var y = biHeight;
		var fromCharCode = String.fromCharCode;

		do {
			var iOffsetY = biWidth4*(y-1);
			var strPixelRow = '';
			for (var x = 0; x < biWidth; x++) {
				var iOffsetX = x<<2;
				strPixelRow += fromCharCode(aImgData[iOffsetY+iOffsetX+2]) +
							   fromCharCode(aImgData[iOffsetY+iOffsetX+1]) +
							   fromCharCode(aImgData[iOffsetY+iOffsetX]);
			}

			for (var c = 0; c < iPadding; c++) {
				strPixelRow += String.fromCharCode(0);
			}

			strPixelData += strPixelRow;
		} while (--y);

		var strEncoded = encodeData(BITMAPFILEHEADER.concat(BITMAPINFOHEADER)) + encodeData(strPixelData);

		return strEncoded;
	};

	/**
	 * saveAsImage
	 * @param canvasElement
	 * @param {String} image type
	 * @param {Number} [optional] png width
	 * @param {Number} [optional] png height
	 */
	var saveAsImage = function (canvas, width, height, type) {
		if ($support.canvas && $support.dataURL) {
			if (typeof canvas == "string") { canvas = document.getElementById(canvas); }
			if (type == undefined) { type = 'png'; }
			type = fixType(type);
			if (/bmp/.test(type)) {
				var data = getImageData(scaleCanvas(canvas, width, height));
				var strData = genBitmapImage(data);
				saveFile(makeURI(strData, downloadMime));
			} else {
				var strData = getDataURL(canvas, type, width, height);
				saveFile(strData.replace(type, downloadMime));
			}
		}
	};

	var convertToImage = function (canvas, width, height, type) {
		if ($support.canvas && $support.dataURL) {
			if (typeof canvas == "string") { canvas = document.getElementById(canvas); }
			if (type == undefined) { type = 'png'; }
			type = fixType(type);

			if (/bmp/.test(type)) {
				var data = getImageData(scaleCanvas(canvas, width, height));
				var strData = genBitmapImage(data);
				return genImage(makeURI(strData, 'image/bmp'));
			} else {
				var strData = getDataURL(canvas, type, width, height);
				return genImage(strData);
			}
		}
	};



	return {
		saveAsImage: saveAsImage,
		saveAsPNG: function (canvas, width, height) {
			return saveAsImage(canvas, width, height, 'png');
		},
		saveAsJPEG: function (canvas, width, height) {
			return saveAsImage(canvas, width, height, 'jpeg');
		},
		saveAsGIF: function (canvas, width, height) {
			return saveAsImage(canvas, width, height, 'gif');
		},
		saveAsBMP: function (canvas, width, height) {
			return saveAsImage(canvas, width, height, 'bmp');
		},

		convertToImage: convertToImage,
		convertToPNG: function (canvas, width, height) {
			return convertToImage(canvas, width, height, 'png');
		},
		convertToJPEG: function (canvas, width, height) {
			return convertToImage(canvas, width, height, 'jpeg');
		},
		convertToGIF: function (canvas, width, height) {
			return convertToImage(canvas, width, height, 'gif');
		},
		convertToBMP: function (canvas, width, height) {
			return convertToImage(canvas, width, height, 'bmp');
		}
	};

}();

 完整的一个代码案例:

完整的一个代码案例:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>canvas生成图片</title>
    <style>
    #demo {
        background-color: #fff;
    }

    .red {
        background-color: red;
        width: 50px;
        height: 50px;
    }

    #imgsSave {
        width: 100%;
        height: auto;
        display: block;
    }
    </style>
</head>

<body>
    <div class="demo-container">
        <div id="demo">
            <div class="red"></div>
            <p>如果原来使用百分比设置元素宽高,请更改为px为单位的宽高,避免样式二次计算导致的模糊</p>
            <p>如果原来使用百分比设置元素宽高,请更改为px为单位的宽高,避免样式二次计算导致的模糊</p>
            <p>如果原来使用百分比设置元素宽高,请更改为px为单位的宽高,避免样式二次计算导致的模糊</p>
            <p>如果原来使用百分比设置元素宽高,请更改为px为单位的宽高,避免样式二次计算导致的模糊</p>
            <p>如果原来使用百分比设置元素宽高,请更改为px为单位的宽高,避免样式二次计算导致的模糊</p>
        </div>
    </div>
    <button id="saveImg">截图</button>
    <div id='imgsSave'></div>
</body>

</html>
<script src="jquery-1.11.3.min.js"></script>
<script src="../js/canvas2image.js"></script>
<script src="../js/html2canvas.js"></script>
<script>
$("#saveImg").on("click", function() {
    var dom = $('#demo')[0];
    var scale = window.devicePixelRatio && window.devicePixelRatio > 1 ? window.devicePixelRatio : 2;
    console.log(scale)
    html2canvas(dom, {
            logging: false,
            useCORS: true,
            width: $(dom).width(),
            height: $(dom).height(),
            scale: scale
        })
        .then(function(canvas) {
            var context = canvas.getContext('2d');
            context.mozImageSmoothingEnabled = false;
            context.webkitImageSmoothingEnabled = false;
            context.msImageSmoothingEnabled = false;
            context.imageSmoothingEnabled = false;
            console.log('截图')
            var img = Canvas2Image.convertToImage(canvas, canvas.width, canvas.height, 'jpeg');
            $('#imgsSave').append(img);
            // $('.demo-container').append(img);
        });

})
</script>

 

 

 

细化的一个代码部分

css

#demo{
    background-color: #fff;
}
.red{
   background-color: red;
   width: 50px;
   height: 50px;
}

html

<div class="demo-container">
    <div id="demo">
        <div class="red"></div>
        <p>如果原来使用百分比设置元素宽高,请更改为px为单位的宽高,避免样式二次计算导致的模糊</p>
        <p>如果原来使用百分比设置元素宽高,请更改为px为单位的宽高,避免样式二次计算导致的模糊</p>
        <p>如果原来使用百分比设置元素宽高,请更改为px为单位的宽高,避免样式二次计算导致的模糊</p>
        <p>如果原来使用百分比设置元素宽高,请更改为px为单位的宽高,避免样式二次计算导致的模糊</p>
        <p>如果原来使用百分比设置元素宽高,请更改为px为单位的宽高,避免样式二次计算导致的模糊</p>
    </div>		
</div>
<button id="saveImg">截图</button>

js

<script src="js/common/jquery-2.1.4.js"></script>
<script src="./html2canvas.min.js"></script>
<script src="./canvas2image.js"></script>
<script type="text/javascript">
      $("#saveImg").on("click", function() {
        var getPixelRatio = function(context) {     // 获取设备的PixelRatio
            var backingStore = context.backingStorePixelRatio ||
                context.webkitBackingStorePixelRatio ||
                context.mozBackingStorePixelRatio ||
                context.msBackingStorePixelRatio ||
                context.oBackingStorePixelRatio ||
                context.backingStorePixelRatio || 1;
            return (window.devicePixelRatio || 1) / backingStore;
        };
        var shareContent = $("#demo")[0]; 
        var width = shareContent.offsetWidth; 
        var height = shareContent.offsetHeight; 
        var canvas = document.createElement("canvas"); 
        var context = canvas.getContext('2d'); 
        var scale = getPixelRatio(context);    //将canvas的容器扩大PixelRatio倍,再将画布缩放,将图像放大PixelRatio倍。
        canvas.width = width * scale; 
        canvas.height = height * scale;
        canvas.style.width = width + 'px';
        canvas.style.height = height + 'px';
        context.scale(scale, scale);
 
        var opts = {
            scale: scale, 
            canvas: canvas,
            width: width, 
            height: height,
            dpi: window.devicePixelRatio
        };
        html2canvas(shareContent, opts).then(function (canvas) {
            context.mozImageSmoothingEnabled = false;
            context.webkitImageSmoothingEnabled = false;
            context.msImageSmoothingEnabled = false;
            context.imageSmoothingEnabled = false;
            var dataUrl = canvas.toDataURL('image/jpeg', 1.0);
            var newImg = document.createElement("img");
            newImg.src =  dataUrl;
            newImg.width = width;
            newImg.height= height;
            $("body")[0].appendChild(newImg);
          });
 
      })
</script>

上述代码中,通过设置canvas的容器为设备 的PixelRatio倍,再将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的背景颜色,如果没有设定默认透明
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--这个我也不知道是干嘛的
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>html2canvas example</title>
    <script type="text/javascript" src="html2canvas.js"></script>
</head>
<script type="text/javascript">
function takeScreenshot() {
  console.log('test');
    html2canvas(document.getElementById('view'), {
        onrendered: function(canvas) {
            document.body.appendChild(canvas);
        },
      // width: 300,
      // height: 300
    });
}
</script>
<body>
    <div id="view" style="background:url(test.jpg) 50%; width: 700px; height: 500px;">
        <input type="button" value="截图" onclick="takeScreenshot()">
    </div>
</body>

</html>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值