Fangraph最近从在表格中显示热图切换到在画布元素中显示它们 . 当热图采用表格格式时,我通过迭代每个td来重新着色它,如下所示:

$('.coloredElement').each(function(){
    var number = +($(this).text());
    if(number > 0.099) {
        $(this).parent("td").css({"background-color": "niceColor", "color":"awesomeColor"});
    } else if (number > 0.089) {
        $(this).parent("td").css({"background-color": "anotherColor", "color":"yetAnotherColor"});
    } else if (...etc) { 
        ...etc
    }
});

这是the new heatmap format的一个示例,其中canvas元素显然用脚本着色:

var canvas = document.getElementById("gridCanvas");                                         
var ctx = canvas.getContext("2d");                                         
ctx.fillStyle="#fff"; ctx.fillRect(0,0,600,675);                                        
ctx.fillStyle="#000"; ctx.font = "15px Arial";                
ctx.fillText("Mike Trout AVG/P vs All Pitchers", 5, 20);                
ctx.fillText("Season: 2017-04-03 to 2017-10-01", 5, 40);                
ctx.fillText("Count: All Counts | Total Pitches: 2597 | View: Catcher", 5, 60);         
ctx.fillStyle="#0000FF";     
etc...

是否可以使用普通的javascript或jQuery基于 ctx.fillText 重新着色 ctx.fillStylectx.fillText 对于画布的相关部分采用 ctx.fillText(".062",270,220) 格式,字符串".062"(表示玩家在打击区域中的平均值),是我将颜色基础的部分 .

或者可以用PHP来解决这个问题吗?它告诉我,如果我检索每个脚本及其相应的热图,则可能以编程方式将其他东西(例如)蓝色替换为其他实例 . 为此,我使用simple html dom,解析出脚本并将其内部文本设置为变量( canvas_script ) . 我已经尝试使用 str_replacepreg_replace 来改变变量包含的字符串中的颜色,但我必须犯错,因为当我回显出结果 canvas_script 时,原始颜色保持不变 . 这是我尝试使用PHP:

include_once('../SHD/simple_html_dom.php');
$url       = "pathToHeatmap";
$context    = stream_context_create();  
stream_context_set_params($context, array('user_agent' => 'my_identity_location_and_purpose'));
$html       = file_get_html($url, 0, $context);
if($html) {
    foreach($html->find('#gridCanvas') as $heat) {
        echo '<div style="text-align: center;">' . $heat . '</div>'; // center map on page
    }

    $s = 1; // increment this variable to loop through script elements in DOM
    foreach($html->find('#content > script') as $script) {
        if($s === 9) { 
            $canvas_script_raw = $script->innertext; 
            $canvas_script     = str_replace("#0000ff", "#4F261B", $canvas_script_raw); // tried to replace blue with something else
            $canvas_script     = preg_replace('/#0000ff/', '#4F261B', $canvas_script_raw); // tried a different method
        }
        $s++;
    }
} else {
    // if the request fails print error message
}

我还研究了使用Gradientmaps.js,它似乎在将图像转换为灰度后重新着色基于亮和暗值的图像 . 然而,随着每个音高数的平均值( ctx.fillText )上升,其相应颜色的值不会产生令人满意的渐变 .