【问题标题】:HTML Canvas: Drawing grid below a plotHTML Canvas:在绘图下方绘制网格
【发布时间】:2013-03-17 04:46:06
【问题描述】:

我正在画布上绘制图表,但无法在图表下方绘制图表网格。我的数据点被绘制为矩形(fillRect)。当我第一次绘制图表然后绘制网格时,它按预期工作,但由于网格在图表上,它看起来并不好。但是当我先画网格再绘制图形时,所有的网格都消失在下面了。

我的情节如下:

var plots = document.getElementsByClassName("PlotCanvas");
for (var x=0; x < tokens.length; x++)
    {
        var canvas = plots[x];
        canvas.width = arrayOfArrays[x].length;
        var context = canvas.getContext("2d");

        for(var point=1; point<arrayOfArrays[x].length; point++)
        {
            context.fillRect(point, arrayOfArrays[x][point],...);
        }
    }

然后将网格绘制为: 函数 DrawGrids(绘图) {

    for(var count=0; count<plots.length; count++)
    {
        var ctx = plots[count].getContext("2d");
        ctx.beginPath();

        for (var x = 0.5; x < plots[count].width; x += 20) {
            ctx.moveTo(x, 0);
            ctx.lineTo(x, plots[count].height);
        }
        for (var y = 0.5; y < plots[count].height; y += 20) {
            ctx.moveTo(0, y);
            ctx.lineTo(plots[count].width, y);
        }
        ctx.strokeStyle = "#eee";
        ctx.stroke();
    }
}

有人可以建议我如何在情节下方绘制网格。或者如何绘制图形,使其不在整个画布上绘制,从而使之前绘制的网格消失。

谢谢。

【问题讨论】:

  • 也许我只是落后于时代,但我认为fillRect 需要四个参数。你只通过了两个。那是怎么回事?
  • 谢谢抢。是的,它确实。为了清楚起见,我没有把它们放在这里,因为我对最后两个参数的计算相当混乱。

标签: javascript html canvas plot


【解决方案1】:

使用 ctx.globalCompositeOperation="destination-over" 在地块后面绘制网格!

// draw your plots here

// save the context
ctx.save();

// set compositing to "destination-over"
// New drawings are drawn behind the existing canvas content.
ctx.globalCompositeOperation = "destination-over";

// draw your grids behind your plots!
DrawGrids();

// restore the context
ctx.restore();

【讨论】:

  • 谢谢markE。有效。我不知道 globalCompositeOperation 属性。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-15
  • 1970-01-01
相关资源
最近更新 更多