首页 > 网站 > WEB开发 > 正文

html转image--通过html2canvas在浏览器端处理

2024-04-27 15:05:11
字体:
来源:转载
供稿:网友

将html显示截取成图片保存,可以在服务器端实现(这种方式的实现和缺点在另一篇博客中介绍了),同样也可以在浏览器端实现;在浏览器端实现无疑减少的服务器压力。

在浏览器实现需要借助第三方 html2canvas,它的使用方式请参考链接。

http://codepedia.info/convert-html-to-image-in-jquery-div-or-table-to-jpg-png/

核心流程

1,Download and import HTML2Canvas jquery files.2,Add HTML markup.3,jQuery Code: Button click convert HTML to Canvas.4,jQuery Code: Download HTML to IMAGE.

整个实现流程:

screenshot->get image binary->image binary to blob object-> blob object to file object->upload

<style>.size-table-page { overflow:hidden; max-width:1100px;margin:20px 100px; }.size-table-page .screenshot-div { display:inline-block; }.size-table-page table { background-color:#fff; }.size-table-page table tr td { width:60px; max-width:10%; height:30px; line-height:30px; text-align:center; font-size:13px; padding:3px 6px; border:1px solid #000; }.size-table-page table tr:first-child td { font-weight:bold; font-size:14px;}.size-table-page table .td-bold { font-weight:bold; font-size:14px;}</style><div class="size-table-page">    <div class="screenshot-div">        <table>            <tbody>                <tr>                    <td class="td-bold">尺寸</td>                    <td >肩宽</td>                    <td >袖长</td>                    <td >下摆</td>                    <td >总长</td>                </tr>                <tr>                    <td class="td-bold">S</td>                    <td >100</td>                    <td >110</td>                    <td >120</td>                    <td >130</td>                </tr>                <tr>                    <td class="td-bold">M</td>                    <td >120</td>                    <td >130</td>                    <td >140</td>                    <td >150</td>                </tr>                        </tbody>        </table>        <div style="width:100px;height:10px;">&nbsp;</div><!-- 尺码表图片和下面的商品详情图片留白用,如果不需要的话,直接截取table的就行了 -->    </div>    <div style="margin-top: 30px;position:fixed;bottom:50px;right:50px"><!--        <a id="btn-convert-html2image" href="#">下载图片到本地</a> -->        <input type="button" class="btn btn-blue btn-small" value="上传至服务器" onclick="uploadSizeTabelImage();">    </div></div><div id="division_area" style="display:none;"></div><script type="text/javascript" src="/xxxxx/js/html2canvas.js"></script><script type="text/Javascript">var element = $(".screenshot-div");var getCanvas;jQuery(document).ready(function(){    html2canvas(element, {        onrendered: function (canvas) {               getCanvas = canvas;            }        });});// $("#btn-convert-html2image").on('click', function () {//     var imgageData = getCanvas.toDataURL("image/png");//     var newData = imgageData.replace(/^data:image//png/, "data:application/octet-stream");//     $("#btn-convert-html2image").attr("href", newData)//     $("#btn-convert-html2image").attr("download", "size_table.png");// });function uploadSizeTabelImage(){//  var imgageData = getCanvas.toDataURL("image/jpeg", 1.0);//  var imgageData = getCanvas.toDataURL("image/png");//  var imgageData = getCanvas.toDataURL();//default is image/png    var dataURL = getCanvas.toDataURL("image/png");    var blobBin = atob(dataURL.split(',')[1]);    var array = [];    for(var i = 0; i < blobBin.length; i++) {        array.push(blobBin.charCodeAt(i));    }    var file=new Blob([new Uint8Array(array)], {type: 'image/png'});    var generatedFile = new File([file], "test.png", {type: 'image/png'}); //test.png 对应后台$_FILES['up']['name'] 用作设定图片的后缀名    var params = {        'up' : generatedFile    }    jQuery('.size-table-page').mask('Uploading...');    fileUploadXhr({        url: '/PRoduct.php'        , type: 'POST'        , cache: false        , dataType : 'json'        , resetForm : true        , clearForm : true        , includeHidden : false//      , uploadProgress : function(e, position, total, percent) { console.log(total + " : " + percent); }        , success : function(obj, status, xhr) {            jQuery('.size-table-page').unmask();            alert('上传成功');            window.close();        }        , error : function(xhr, status, error) {            jQuery('.size-table-page').unmask();            alert('上传失败.');        }    }, params);}

function fileUploadXhr(options, params) {    var formdata = new FormData();    for(i in params) {        formdata.append(i, params[i]);    }    var s = jQuery.extend(true, {}, jQuery.AjaxSettings, options, {        contentType: false,        processData: false,        cache: false,        type: options.type    });    if (options.uploadProgress) {        // workaround because jqXHR does not expose upload property        s.xhr = function() {            var xhr = jQuery.ajaxSettings.xhr();            if (xhr.upload) {                xhr.upload.addEventListener('progress', function(event) {                    var percent = 0;                    var position = event.loaded || event.position; /*event.position is deprecated*/                    var total = event.total;                    if (event.lengthComputable) {                        percent = Math.ceil(position / total * 100);                    }                    options.uploadProgress(event, position, total, percent);//                    log(total + " : " + percent);                }, false);            }            return xhr;        };    }    s.data = null;    var beforeSend = s.beforeSend;    s.beforeSend = function(xhr, o) {        //Send FormData() provided by user        if (options.formData) {            o.data = options.formData;        }        else {            o.data = formdata;        }        if(beforeSend) {            beforeSend.call(this, xhr, o);        }    };    return jQuery.ajax(s);}

</script>

备注:

这种方式提交的时候,不同的域名间提交数据会发生如下问题:已拦截跨源请求:同源策略禁止读取位于 xxxxxxxxx的远程资源。(原因:CORS 头缺少 'access-Control-Allow-Origin')。题主所说的跨域问题需要在提供服务的后端解决,前端是无法解决的。需要在后端设置responce的HEAD中Access-Control-Allow-Origin,设置允许跨域的域名。跨域是需要前后端一同协作的。  解决方案,在file服务器上传文件的开头添加如下代码.    if(isset($_SERVER['HTTP_ORIGIN']) && in_array($_SERVER['HTTP_ORIGIN'], array('域名'))) {        header("Access-Control-Allow-Origin: ".$_SERVER['HTTP_ORIGIN']."/r/n");        header("Access-Control-Allow-Methods: POST/r/n");        header("Access-Control-Max-Age: 86400/r/n");    }


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表