【问题标题】:Confusion with html2canvas与 html2canvas 混淆
【发布时间】:2014-04-15 14:50:14
【问题描述】:

我有这个相当简单的 javascript/html 代码。我想用“id = mapDiv”保存div,将地图显示为图像(jpg或png)。我在 html 文件的根目录中有 'jquery-1.11.0.js' 和 'html2canvas.js' 文件。我对 HTML/Javascript 缺乏经验,无法理解人们之前发布的一些解决方案。任何帮助将不胜感激。谢谢!

这是我的代码:

<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

        <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

        <script type="text/javascript">

            function GetMap()
            {

                var lat1 = document.getElementById("lat1").value;
                var lon1 = document.getElementById("lon1").value;

                var lat2 = document.getElementById("lat2").value;
                var lon2 = document.getElementById("lon2").value;

                // Initialize the map


                var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"At7RkDItXU6kncQzZa8M9lFfMbzPgmulJYLkhYn5JMMZfHL86lNyFZvGWWngxaAP",
                                                 bounds:new Microsoft.Maps.LocationRect.fromCorners(new Microsoft.Maps.Location(lat1, lon1), new Microsoft.Maps.Location(lat2, lon2)),
                                                 zoom: 20,
                                                 mapTypeId: Microsoft.Maps.MapTypeId.aerial,
                                                 disableZooming: true,
                                                 showCopyright: false,
                                                 showDashboard: false,
                                                 enableClickableLogo: false,
                                                 });

                try
                {
                    // Create the tile layer source
                    var tileSource = new Microsoft.Maps.TileSource({uriConstructor: 'http://www.microsoft.com/maps/isdk/ajax/layers/lidar/{quadkey}.png'});

                    // Construct the layer using the tile source
                    var tilelayer= new Microsoft.Maps.TileLayer({ mercator: tileSource, opacity: .7 });

                    // Push the tile layer to the map
                    map.entities.push(tilelayer);





                    // Disable mouse click and pan map
                    Microsoft.Maps.Events.addHandler(map, 'mousedown', function (mouseEvent) {
                    mouseEvent.handled = true; 
                    }); 

                    // Calculating distance between two points
                    function toRad(Value) {
                    return Value * Math.PI / 180;}

                    // Calculate vertical distance
                    var vR = 6371; // km
                    var vdLat = toRad(lat2-lat1);
                    var vdLon = toRad(lon1-lon1);
                    var vrlat1 = toRad(lat1);
                    var vrlat2 = toRad(lat2);

                    var va = Math.sin(vdLat/2) * Math.sin(vdLat/2) +
                    Math.sin(vdLon/2) * Math.sin(vdLon/2) * Math.cos(vrlat1) * Math.cos(vrlat2); 
                    var vc = 2 * Math.atan2(Math.sqrt(va), Math.sqrt(1-va)); 
                    var vd = vR * vc;   

                    //Calculate horizontal distance
                    var hR = 6371; // km
                    var hdLat = toRad(lat1-lat1);
                    var hdLon = toRad(lon2-lon1);
                    var hrlat1 = toRad(lat1);
                    var hrlat2 = toRad(lat1);

                    var ha = Math.sin(hdLat/2) * Math.sin(hdLat/2) +
                    Math.sin(hdLon/2) * Math.sin(hdLon/2) * Math.cos(hrlat1) * Math.cos(hrlat2); 
                    var hc = 2 * Math.atan2(Math.sqrt(ha), Math.sqrt(1-ha)); 
                    var hd = hR * hc;

                    alert(' Horizontal Distance = ' + hd + '\n Vertical Distance = ' + vd);

                }
                catch(err)
                {
                    alert( 'Error Message:' + err.message);
                }
            }

            </script>

            <script type="text/javascript" src="html2canvas.js"></script>
            <script type="text/javascript" src="jquery-1.11.0.js"></script>

            <script type="text/javascript">
                    $(document).ready(function() {
                    var target = $('div');
                    html2canvas(target, {
                    onrendered: function(canvas) {
                    var data = canvas.toDataURL();
                    var myImage = canvas.toDataURL("image\png");
                    window.open(myImage);
                    //alert(data);
                    //data is the Base64-encoded image
                    }
                    });
                    });
            </script> 


        </head>

<body onload="GetMap();">
<body bgcolor="#9FB6CD">
    <center>
        <h1>Enter Coordinates</h1>
        </br>
        <h3>Input points</h3>
        Coordinate1 (upper-left):
        </br>
        latitude 1: <input type="text" id="lat1" value="55"><br>
        Longitude 1: <input type="text" id="lon1" value="135"><br>
        Coordinate 2 (lower-right):
        </br>
        latitude 2: <input type="text" id="lat2" value="54.98"><br>
        Longitude 2: <input type="text" id="lon2"value="135.02"><br>
        <input type="submit" value="submit" onclick="GetMap()">

    <div id='mapDiv' typename="mapDiv" style="position:relative; width:500px; height:500px;"></div>

    <script>
        $('#mapDiv div.mapDiv').trigger($.event('click'));
    </script>
    </center>
</body>
</html>

【问题讨论】:

    标签: javascript html image maps html2canvas


    【解决方案1】:

    如果您想将图像从画布保存为某种图像格式,这里对您有一些帮助。希望对您有所帮助。

    $(document).ready(function() {
    
        html2canvas(document.getElementById('mapDiv'), {
                onrendered: function(canvas) {
                    var cs = new CanvasSaver('save_img.php',canvas,'myimage')
                }
            });
    
    });
    

    这里 CanvasSaver() 函数定义在下面,它带有三个参数,一个是一个 php 文件,它将图像从 RAW 日期处理为某种图像格式。我将在此脚本部分编写“save_img.php”的代码并将该文件保存在您的根目录中。

    function CanvasSaver(url, cnvs, fname) {
    
        this.url = url;
    
        if(!cnvs || !url) return;
        fname = fname || 'picture';
    
        var data = cnvs.toDataURL("image/png");
        data = data.substr(data.indexOf(',') + 1).toString();
    
        var dataInput = document.createElement("input") ;
        dataInput.setAttribute("name", 'imgdata') ;
        dataInput.setAttribute("value", data);
        dataInput.setAttribute("type", "hidden");
    
        var nameInput = document.createElement("input") ;
        nameInput.setAttribute("name", 'name') ;
        nameInput.setAttribute("value", fname + '.jpg');
    
        var myForm = document.createElement("form");
        myForm.method = 'post';
        myForm.action = url;
        myForm.appendChild(dataInput);
        myForm.appendChild(nameInput);
    
        document.body.appendChild(myForm) ;
        myForm.submit() ;
        document.body.removeChild(myForm) ;
    
    }
    

    在上面的脚本中,无论您想从浏览器保存什么图像格式,都在上面的脚本函数中给出该图像扩展名

    nameInput.setAttribute("value", fname + '.jpg');
    

    现在这里是您的“save_img.php”的代码并将其保存在您的根目录中。

    <?php
        # we are a PNG image
        header('Content-type: image/png');
    
        # we are an attachment (eg download), and we have a name
        header('Content-Disposition: attachment; filename="' . $_POST['name'] .'"');
    
        #capture, replace any spaces w/ plusses, and decode
        $encoded = $_POST['imgdata'];
        $encoded = str_replace(' ', '+', $encoded);
        $decoded = base64_decode($encoded);
    
        #write decoded data
        echo $decoded;
    ?>
    

    【讨论】:

      猜你喜欢
      • 2014-07-09
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多