jeitu.html 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <title>html2canvas example</title>
  7. <script type="text/javascript" src="../static/html2canvas.js"></script>
  8. <script type="text/javascript" src="../static/jquery-1.7.2.min.js"></script>
  9. </head>
  10. <script type="text/javascript">
  11. var c_width = $('.box').outerWidth();//如果box设置了padding,需要获取outerWidth和outerHeight来赋给canvas;
  12. var c_height =$('.box').outerHeight();
  13. var canvas = document.createElement("canvas");
  14. var context = canvas.getContext("2d");
  15.     //以下代码是获取根据屏幕分辨率,来设置canvas的宽高以获得高清图片
  16. // 屏幕的设备像素比
  17. var devicePixelRatio = window.devicePixelRatio || 2;
  18. // 浏览器在渲染canvas之前存储画布信息的像素比
  19. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  20. context.mozBackingStorePixelRatio ||
  21. context.msBackingStorePixelRatio ||
  22. context.oBackingStorePixelRatio ||
  23. context.backingStorePixelRatio || 1;
  24. // canvas的实际渲染倍率
  25. var ratio = devicePixelRatio/backingStoreRatio;
  26. canvas.width = c_width * ratio;
  27. canvas.height = c_height * ratio;
  28. canvas.style.width = c_width + "px";
  29. canvas.style.height = c_height + "px";
  30. var transTop = $(document).scrollTop() - $('.card_box').offset().top;//获取div垂直方向的位置
  31. context.scale(ratio,ratio);
  32. context.translate((c_width-$(window).width())/2,transTop);//canvas的位置要保证与div位置相同。
  33.     //高清图设置完成
  34.     
  35.    //解决跨域,将跨域图片路径转为base64格式
  36.     var img = new Image();
  37.     var canvas2 = document.createElement('canvas');
  38.     var ctx = canvas2.getContext('2d');
  39.     img.crossOrigin = 'Anonymous';
  40.     img.src=$('#ossImg').attr('src');
  41.     img.onload = function () {
  42.      canvas2.height = img.height;
  43.      canvas2.width = img.width;
  44.      ctx.drawImage(img, 0, 0);
  45.      var dataURL = canvas2.toDataURL('image/png');
  46.       $('#ossImg').attr('src',dataURL);
  47.      canvas2 = null;
  48.     //重新给img赋值成功后,执行截图方法
  49.     getCard()
  50.     };
  51.     function getCard(){
  52.       html2canvas($(".box"),{
  53. allowTaint:true,
  54. useCORS:true,
  55. canvas:canvas,
  56. onrendered:function(canvas){
  57. dataURL =canvas.toDataURL("image/png");
  58. var img = new Image();
  59. img.src=dataURL;
  60. img.className = 'cardImg';
  61. img.onload = function () {
  62. $(".card").append(img);
  63. }
  64. },
  65. width:c_width,
  66. height:c_height
  67. })
  68.    }
  69. </script>
  70. <body>
  71. <div class="box">
  72.   <p>这是生成图片的box,内容不限</p> 
  73. //跨域图片(oss地址)
  74.   <img id="ossImg" src="../image_dir/3.png">
  75. </div>
  76. </body>
  77. </html>