Flot使用与浏览器不同的背景颜色渲染png图像

时间:2014-08-11 21:51:17

标签: canvas flot

在将flot制作的HTML5画布保存为图像格式时,我遇到了一个问题。见下图。

enter image description here

这是我从同一图表的两个不同的再现(使用相同的代码)拼接在一起的图像。左侧是浏览器中的画布,呈现白色。右侧是我使用getCanvas()代码将数据保存为图像形式并将其渲染为灰色。我无法解释颜色的差异,也无法解决它。您认为这个问题是什么?

更多信息

//JS side:
var plot = $.plot($("#plot"), flotData, flotOptions);
var canvas = plot.getCanvas();
var data = canvas.toDataURL("image/png");

//I then pass data via dynamically created JS-form to a PHP script
{code ommitted, but essentially $imageData = data}

//once in PHP script:
$parts = explode(',', $imageData);
$data = base64_decode($parts[1]);


header('Content-Type: image/png');
header('Content-Length: '.strlen($data));

// Output the actual image data //renders with gray instead of white(!!)
echo $data;

观察

发现我可以在flot中设置背景颜色:

grid:{"backgroundColor" : {"colors" : [ "#FFF", "#EEE" ]}}

但是它只改变了网格内部的颜色,网格两侧的垂直边线(轴)在浏览器渲染时为白色时仍然具有灰色背景。

另一种攻击方法是找到一种“在现有画布上绘制flot图表”的方法。制作帆布,将其着色,将其传递给flot。 (不知道是否可能)

**更新! **

我在这里遇到的问题是“透明度”。 Alpha通道上带有0的透明像素获得了我想要避免的这种颜色。

1 个答案:

答案 0 :(得分:3)

啊,所以答案就是透明度。当我尝试将图像导出为“jpeg”并且边框颜色不同(黑色)时,必须为我点击某些内容。对于网格外的边界,PNG的alpha通道为0。因此,其他程序可以自由地在那里写东西。

我的解决方案受到http://www.patrick-wied.at/blog/how-to-create-transparency-in-images-with-html5canvas的启发,我通过Google搜索“canvas png transparency”找到了该解决方案。

我的代码是这样的:

var image = context.getImageData(0, 0, canvas.width, canvas.height);

for(var i=0; i < image.data.length; i+=4)
{ 
    if (image.data.[i+3] == 0)  //if transparent
    {
        image.data[i] = 255;    //blast the mfkr with full on white!
        image.data[i+1] = 255;
        image.data[i+2] = 255;
        image.data[i+3] = 255;
    }
}

原油,但是做到了!