实现[微信]H5长按保存图片功能

时间:2025-04-02 17:00:12
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="format-detection" content="telephone=no" /> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <title>截图功能</title> </head> <script src="/js/"></script> <body> <!-- 放置图片容器 --> <div > <div class="poster_box"> <img src="/" alt=""> </div> </div> </body> </html> <script src="/html2canvas/"></script> <script> // 创建一个新的canvas let Canvas = ('canvas'); let width = ('canvasContainer').width; // 画布指定区域的宽 let height = ('canvasContainer').height; // 画图指定区域的高 let scale = DPR(); // 设备的devicePixelRadio // 将Canvas画布放大scale倍,然后放在小的屏幕里,解决模糊问题 = width * scale; = height * scale; ('2d').scale(scale, scale); html2canvas(('canvasContainer'),{ canvas: Canvas, scale, logging: true, useCORS:true, // 允许使用跨域图片 allowTaint: false, // 不允许跨域图片污染画布 width: width + 'px', height: height + 'px', }).then(function(canvas) { let context = ('2d'); // 关闭抗锯齿形 = false; = false; = false; = false; // canvas转化为图片 let canvasImg = canvas2Image(canvas, , ); (canvasImg); $(canvasImg).css('width','100%') .css('height','100%') .css('position','absolute') .css('top','0') .css('left','0') .css('right','0') .css('bottom','0') .css('opacity','0'); }) /** * 画步转换成图片 */ function canvas2Image(canvas, width, height) { let retCanvas = ('canvas'); let retCtx = ('2d'); = width; = height; (canvas, 0, 0, width, height, 0, 0, width, height); let img = ('img'); = ('image/jpeg'); // 可以根据需要更改格式 return img; } /** * 根据获取像素比 */ function DPR() { if ( && > 1) { return ; } return 1; } </script>