以下需要用到html2canvas.js库请自行前往下载。

下面例子用的是html2canvas 0.5.0-beta3 <http://html2canvas.hertzen.com>。

思路:先获取到手机的PixelRatio,然后生成时尺寸做相应调整,就可以生成清晰的图片了。

var getPixelRatio = function(context) {
				var backingStore = context.backingStorePixelRatio ||
					context.webkitBackingStorePixelRatio ||
			    	context.mozBackingStorePixelRatio ||
			    	context.msBackingStorePixelRatio ||
			    	context.oBackingStorePixelRatio ||
			    	context.backingStorePixelRatio || 1;
				return (window.devicePixelRatio || 1) / backingStore;
			};
			var canvas = document.createElement('canvas');
			var context = canvas.getContext('2d');
			var scaleBy = getPixelRatio(context);
			var w = $("#screenshot").width();
			var h = $("#screenshot").height();
			canvas.width = w * scaleBy;
			canvas.height = h * scaleBy;
			canvas.style.width = w + 'px';
			canvas.style.height = h + 'px';
			context.scale(scaleBy, scaleBy);
			html2canvas(document.getElementById("screenshot"), {
			    canvas:canvas,
			    onrendered: function(canvas) {
			        var dataUrl = canvas.toDataURL();
			        var newImg = document.createElement("img");
					newImg.id = "share-pic";
			        newImg.src =  dataUrl;
			        newImg.width=w;
			        newImg.height=h;
			        $("body")[0].appendChild(newImg);
			    }
			});

1 对 “html2canvas网页保存生成清晰的图片”的想法;

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Scroll Up