html长按保存页面,html2canvas实现(图文组合)图片长按保存

demo实现

* {

padding: 0;

margin: 0;

box-sizing: border-box;

}

html,

body {

width: 100%;

height: 100%;

background: #f2f2f2;

}

#box {

width: 100%;

height: 100%;

display: flex;

align-items: center;

justify-content: center;

flex-direction: column;

}

#cBox {

width: 80%;

height: 60%;

border: 1px solid #c00;

display: flex;

justify-content: center;

flex-direction: column;

align-items: center;

}

.img {

max-width: 100%;

}

.img1 {

height: 20%;

}

.img2 {

height: 30%;

}

.img3 {

height: 20%;

}

p {

padding: 10px;

}

button {

background-color: #ccc;

padding: 10px 20px;

outline: 0;

border-radius: 6px;

margin-top: 50px;

color: #c00;

font-size: 17px;

}

#saveImg {

position: absolute;

border: 1px solid #00f;

width:80%;

height: 60%;

margin-top: -50px;

opacity: 0;

}

测试div保存图片功能

长按保存图片

var box = document.getElementById("box");

var el = document.getElementById("cBox");

var saveImg = document.getElementById("saveImg");

var canvas = document.createElement("canvas");

var scale = window.devicePixelRatio;

var ctx=canvas.getContext("2d")

var rect = el.getBoundingClientRect(); //获取元素相对于视察的偏移量

var w = el.offsetWidth;

var h = el.offsetHeight;

canvas.width = w * scale;

canvas.height = h * scale;

canvas.style.width = w ;

canvas.style.height = h ;

ctx.scale(scale, scale);

ctx.translate(-rect.left,-rect.top); //设置context位置,值为相对于视窗的偏移量负值,让图片复位

html2canvas(el, {

scale: scale,

canvas: canvas,

width: w,

height: h,

logging: false,

background: "#f2f2f2",

useCORS: true

}).then(function (canvas) {

var dataUrl = canvas.toDataURL("jpeg");

saveImg.src=dataUrl;

});

效果图如下(红框位置为需要保存的内容)

bfb7d520c402

效果图

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值