做对账单,很好!
<div id="qu"><p>今天是什么日子亚</p></div>
/*自备jq*/
<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.min.js"></script>
<script>
var dataurl;
var canvas2 = document.createElement("canvas");
/*let _canvas = $("#qu");*/
let my_div = $("#qu");
/*let style = window.getComputedStyle(my_div, null);*/
var w = $(window).width()/*$("#qu").width()*/;
var h = $(window).height()/*$("#qu").height()*/;
console.log(w+"-"+h)
//将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了
canvas2.width = w * 2;
canvas2.height = h * 2;
canvas2.style.width = w + "px";
canvas2.style.height = h + "px";
//可以按照自己的需求,对context的参数修改,translate指的是偏移量
// var context = canvas.getContext("2d");
// context.translate(0,0);
var context = canvas2.getContext("2d");
context.scale(2, 2);
/* alert(w)
*/ html2canvas($("#qu"), { canvas: canvas2 }).then(function(canvas) {
//document.body.appendChild(canvas);
//canvas转换成url,然后利用a标签的download属性,直接下载,绕过上传服务器再下载
dataurl = canvas.toDataURL();
var ob={
"type":1,
"billfileurl":dataurl, // base64
}
// 上传服务端
$.ajax({
type: "POST",
url: ".../api/uploadPhoto",
data: ob,
success: function (data) {
}
})
</script>
服务端:
public String saveImg(String baseImg) {
//定义一个正则表达式的筛选规则,为了获取图片的类型
String rgex = "data:image/(.*?);base64";
String type = getSubUtilSimple(baseImg, rgex);
//去除base64图片的前缀
baseImg = baseImg.replaceFirst("data:(.+?);base64,", "");
byte[] b;
byte[] bs;
OutputStream os = null;
String fileName = "";
String nowDate = "";
// 格式化并获取当前日期(用来命名)
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMddHHmmss");
nowDate = format.format(new Date());
//把图片转换成二进制
b = Base64.decodeBase64(baseImg.replaceAll(" ", "+"));
/* SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMddHHmmss");*/
//生成路径E://data//C:\canteenWeb\canteenWeb\billimg E:/project/Web/canteenWeb/canteenWeb/billimg
String path = "E:/project/Web/canteenWeb/canteenWeb/billimg";// + separator + nowDate + separator;
//随机生成图片的名字,同时根据类型结尾
fileName = format1.format(new Date()) + "." + type;
File file = new File(path);
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
File imageFile = new File(path + "/" + fileName);
BASE64Decoder d = new BASE64Decoder();
// 保存
try {
bs = d.decodeBuffer(Base64.encodeBase64String(b));
os = new FileOutputStream(imageFile);
os.write(bs);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.getLocalizedMessage();
}
}
}
return "billimg/"+fileName;
}
public static String getSubUtilSimple(String soap, String rgex) {
// 校验
Pattern pattern = Pattern.compile(rgex);
Matcher m = pattern.matcher(soap);
while (m.find()) {
return m.group(1);
}
return "png";
}