为什么符号在浮动图形中呈现三次?

时间:2013-07-10 16:13:19

标签: javascript flot symbols

我正在使用flot库来渲染PNG图像呈现为点的图。它工作正常,但每个PNG图像似乎渲染了三次。这在刷新时是可见的(重叠不完美),我还记录了图像的onload函数,Firebug告诉我每个图形被调用三次。这是渲染图像的函数(计数器是记录变量):

function generateImageFunction (image) {
    return function getImage(ctx, x, y, radius, shadow) {                   
        var img = new Image();
        img.onload = function() {
            console.log(counter++);
            ctx.drawImage(img, x, y, img.width, img.height);    
        }
        img.src = image;
    }
}

数据有13个系列,这些只是前两个例子:

var data = [
            { 
             data: [[1, 1]], 
             points: { symbol: generateImageFunction("face-angel.png") }
            }
            { 
             data: [[2, 2]], 
             points: { symbol: generateImageFunction("face-angry.png") }
            }
           ];

我的选择是这些:

var options = {
               series: {
                   points: { show: true },
               },
               xaxis: { min: 0, max: 15},
               yaxis: { show: false, min: 0, max: 15 },
               selection: { mode: "x" }
};

然后我做$.plot($("#placeholder"), data, options);

对于13个数据系列,当我第一次加载页面时,计数器变量变为39。如果我放大只有一个数据点的区域,计数器会增加3.有人可以告诉我为什么会这样,或者我可以进一步调查什么?

2 个答案:

答案 0 :(得分:5)

每次flot使用该点时,您的代码所做的就是重新下载图像。不可否认,flot可能不应该每$.plot次电话使用3次,但是你可以做的并不多!你能做的只是加载一次图像!

function generateImageFunction(image) {
    return function getImage(ctx, x, y, radius, shadow) {
        ctx.drawImage(image, x, y, image.width, image.height);
    }
}

//list out all used images here
var symbols = {
    'icon1': 'http://tinychat.com/public/images/star.png',
        'icon2': 'http://www.earthdetails.com/images/icons/X-16-01.gif'
};
var symbol2image = {};//used to reference the downloaded image
var loading = [];//just used in the $.load call

//start loading each image
for (var symbol in symbols) {
    var img = new Image();
    img.src = symbols[symbol];
    symbol2image[symbol] = img;
    loading.push(img);
}

//wait until they are all loaded, then call the plot function
$.apply($, loading).load(function () {

   //setup data/options here, key lines being how you call the new generateImageFunction
                 symbol: generateImageFunction(symbol2image['icon2'])

   //call plot
    $.plot($("#placeholder"), data, options);
});

这里有一个有效的例子:http://jsfiddle.net/ryleyb/kEhsQ/2/

答案 1 :(得分:4)

除非您覆盖全局或每系列shadowSize选项,否则Flot将在每个系列下方绘制阴影。阴影分两步绘制(搜索plotPoints函数的代码,看看如何完成)增加不透明度,软化边框。

所以你的函数运行一次以在alpha 0.1处绘制阴影,再次以alpha 0.2绘制它,然后再次绘制实际系列。

如果您不想这样,可以通过将shadowSize设置为零来完全禁用阴影。您还可以通过检查函数的'shadow'参数的值来跳过仅绘制点的阴影;如果它是真的,至于用于绘制阴影的两个调用,那么你可以立即返回。

如果你使用后者,那么我肯定也会这样做,因为@Ryley建议避免多次实际加载图像。