数组

时间:2015-08-10 09:41:02

标签: javascript php dygraphs

我有一个名为$ blade的php变量,我为每个刀片创建了一个div和graph:

<div id="$blade" style="width:1000px; height:300px;"></div>

g$blade = new Dygraph(document.getElementById("$blade"),"./Data/$node/$blade.txt",{ legend: 'always', title: '$node-$blade', valueRange: [0, 120],visibility: [true, true]});

我将php刀片变量名保存在javascript变量中:

var blades=[];

    foreach ($mabez_blades as &$blade) {
echo <<<AAA

        <script type="text/javascript">
           blades.push("g$blade");
           //console.log(blades);
        </script>
AAA;

}

console.log(blades) -> ["gSC_2_1", "gSC_2_2", "gPL_2_3", "gPL_2_4", "gPL_2_5", "gPL_2_6", "gPL_2_7", "gPL_2_8", "gPL_2_9", "gPL_2_10"]

我需要制作一个按钮,将所有这些图形转换为图片并下载它们,问题是我可以直接使用它的名称访问一个图形,我无法动态地迭代图形名称。

    <img id="img" style="display:none"/>
    <canvas id="canvas" width="1000" height="300" style="display:none" >canvas</canvas>


    <script type="text/javascript">
        var img = document.getElementById("img"); 
        var canvas = document.getElementById("canvas");
        canvas.style.display="none";
        var ctx = canvas.getContext("2d");
function saveImage() {
    blades.forEach(function(entry) {
            var filename = entry+".png";
            //Dygraph.Export.asPNG(gSC_2_1, img); //this works for a single graph download
            //Dygraph.Export.asPNG(entry, img); //this doesn't work
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(img, 0, 0);
            var link = document.createElement('a');
            link.download = filename;
            link.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
            link.click();
            });
};
    </script>

它产生以下错误:

Uncaught Type Error: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'

1 个答案:

答案 0 :(得分:0)

我找到了问题的答案,因为我使用$ blade作为div id,它被认为是div元素而不仅仅是一个字符串。所以我将图形元素放在一个带有$ blade和value的对象中,因为图形对象也将div id从$ blade更改为div $ blade。 如果有人有更好的建议,我会感谢他/她。

<div id="div$blade" style="width:1000px; height:300px;"></div>

<script type="text/javascript">
var graphs={};
graphs.$blade = new Dygraph(document.getElementById("div$blade"),"./Data/$node/$blade.txt",{ legend: 'always', title: '$node-$blade', valueRange: [0, 120],visibility: [true, true]});

function saveImage() {
            for (var key in graphs){
                    var filename = key+".png";
                    Dygraph.Export.asPNG(graphs[key], img);
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    ctx.drawImage(img, 0, 0);
                    var link = document.createElement('a');
                    link.download = filename;
                    link.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
                    link.click();
                    }}