前台方法使用html2canvas将div转换为图片,点击完成,图片以Ajax Post的方式提交到后台接口。存储到文件目录下。
1.保存的图片效果:
2.前台代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta charset="utf-8" />
<script src="Jscript/jquery-1.8.2.min.js"></script>
<script src="Html2canvas_JS/base64.js"></script>
<script src="Html2canvas_JS/canvas2image.js"></script>
<script src="Html2canvas_JS/html2canvas.min.js"></script>
</head>
<body>
<button id="btn_save">完成</button>
<div id="canvasDiv" style="display: none; height: 520px; 100%;"></div>
<div class="container form-group" id="container" style="height: 520px; 100%; margin: 10px 15px 30px 15px; position: static !important;"></div>
<link rel="stylesheet" href="http://cache.amap.com/lbs/static/main1119.css" />
<script src="http://webapi.amap.com/maps?v=1.4.5&key=xxx&plugin=AMap.MarkerClusterer,AMap.MouseTool,AMap.Geocoder"></script>
<script type="text/javascript" src="http://webapi.amap.com/demos/js/liteToolbar.js"></script>
<script src="http://webapi.amap.com/ui/1.0/main.js"></script>
<script type="text/javascript">
var googleLayerf = new AMap.TileLayer({
getTileUrl: 'http://mt{1,2,3,0}.google.cn/vt/lyrs=s&hl=zh-CN&gl=cn&x=[x]&y=[y]&z=[z]&s=Galile'
});
var roadNetLayerf = new AMap.TileLayer.RoadNet();
var map = new AMap.Map('container',
{
resizeEnable: true,
zoom: 4,
zooms: [3, 21],
layers: [googleLayerf, roadNetLayerf],
center: [103.7822008899, 36.2167828433]
});
function createXMLHttp() {
var objXmlHttp = null;
if (window.ActiveXObject) {
objXmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
if (window.XMLHttpRequest) {
objXmlHttp = new XMLHttpRequest();
} else {
window.alert('初始化XMLHTTP错误!');
}
}
return objXmlHttp;
};
function postAjax(url, formData, isUploadFile, isAsync) {
var result;
var xhr = createXMLHttp();
xhr.open("POST", url, isAsync);
if (isUploadFile) {
xhr.setRequestHeader("Content-type", "multipart/form-data");
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
result = xhr.responseText;
}
}
};
xhr.send(formData);
return result;
};
function toBase64(imgStream) {
var base64Data;
if (imgStream.split(',')[0].indexOf('base64') >= 0)
base64Data = imgStream.split(',')[1];
return base64Data;
};
function createImg() {
html2canvas($('#container'),
{
useCORS: true,
onrendered: function (canvas) {
canvas.setAttribute('id', 'thecanvas');
document.getElementById('canvasDiv').innerHTML = "";
document.getElementById('canvasDiv').appendChild(canvas);
}
});
};
function uploadImg() {
var oCanvas = document.getElementById('thecanvas');
if (oCanvas == null) {
alert('当前环境不支持Canvas!');
return '';
}
var imgStream = oCanvas.toDataURL('image/png', 1.0);
var base64Data = toBase64(imgStream);
if (base64Data == null) {
alert('网络或服务正忙,请稍后重试');
return "";
}
var fileName = Date.parse(new Date()) + '.PNG';
var formData = new FormData();
formData.append('fileName', fileName);
formData.append('file', base64Data);
var url = "UploadImg.ashx";
var result = postAjax(url, formData, false);
result = JSON.parse(result);
if (result['state'] == "success") {
return result['msg'];
}
return "";
};
$(function () {
$('#btn_save').click(function () {
$('#btn_save').attr('disabled', 'disabled');
setTimeout(function () {
createImg();
},500);
setTimeout(function() {
alert(uploadImg());
},1500);
$('#btn_save').attr('disabled', false);
});
});
</script>
</body>
</html>
3.后台代码,一般处理文件UploadImg.ashx
public class UploadImg : IHttpHandler
{
public static void EnsureDirectory(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
public void ImgCrop(byte[] bytes, string targetImgPath)
{
byte[] imgBytes = bytes;
FileStream fileStream = new FileStream(targetImgPath, FileMode.Create, FileAccess.Write);
using (BinaryWriter writer = new BinaryWriter(fileStream))
{
writer.Write(imgBytes);
}
fileStream.Close();
fileStream.Dispose();
}
public void ProcessRequest(HttpContext context)
{
string sourceFileName = context.Request["fileName"];
string file = context.Request["file"];
string guid = Guid.NewGuid().ToString();
string targetImgFileName = guid + "-" + sourceFileName;
string targetImgRelativeFolderStr = "\Images\Upload\MapScreenshot";
EnsureDirectory(HttpContext.Current.Server.MapPath(targetImgRelativeFolderStr));
string targetImgRelativeFolder = HttpContext.Current.Server.MapPath(targetImgRelativeFolderStr);
string targetImgRelativePath = Path.Combine(targetImgRelativeFolderStr, targetImgFileName);
string targetImgPath = Path.Combine(targetImgRelativeFolder, targetImgFileName);
byte[] imgBytes = Convert.FromBase64String(file);
ImgCrop(imgBytes, targetImgPath);
context.Response.ContentType = "application/json";
context.Response.Write("{"state":"success","msg":"上传成功"}");
}
}
4.需要的js文件:
jquery-1.8.2.min.js
base64.js
canvas2image.js
html2canvas.min.js