在画布上填充多边形 [英] Fill polygon on canvas

查看:116
本文介绍了在画布上填充多边形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何填写我用红色绘制的路径?

How can I fill the path that I've drawn in red?

http://jsfiddle.net/MVXZu/1/

我已尝试使用填充,但不填满我的路径,因为我想要它 - 这是填充红色轮廓 - 而是它只填充一个对角线部分(注释ctx.fill();看到完整的轮廓,我想填充)绘制行是这样的:

I've tried to use fill but it doesn't fill my path as I want it to - that is to fill in the red outline - but instead it fills only a diagonal portion (comment out the ctx.fill(); to see the full outline I want to fill) The code that's drawing the line is this:

//loop through the data
ctx.beginPath();
for (var i = 0; i < data.length; i++) {
ctx.lineWidth=3;
ctx.lineCap = 'round';
ctx.strokeStyle = 'red';
ctx.moveTo(linePosX,linePosY);
ctx.lineTo((i*cellWidth) + cellWidth + padding,(tableHeight + padding) - data[i].v);
linePosX = i*cellWidth + padding + cellWidth;
linePosY = (tableHeight + padding) - data[i].v;
if(i == 13) {

    ctx.lineTo(linePosX,tableHeight+padding);
    ctx.lineTo(padding,tableHeight+padding);
}

   ctx.fillStyle="red";
   ctx.fill();
   ctx.stroke();
   ctx.closePath();

}

推荐答案

希望这就是你想要的: http://jsfiddle.net/MVXZu/2/

因为你只是运行一些代码 if(i == 13){} 只有 moveTo 和第一个 lineTo 被调用。这导致在该部分的顶部有一行,但不是一个要填充的框。

Because you were only running some of the code if (i == 13) {}, only the moveTo and the first lineTo were getting called. This was resulting in a line at the top of the section, but not a box to fill.

我将很多绘图移动到循环之外。它在图形的左下方创建第一个点,然后沿顶部创建点,然后在右下方创建点。然后它在路径完成后填充整个图。

I moved a lot of the drawing outside of the loop. It creates the first point in the bottom left of the graph, then the points along the top, then the point in the bottom right. Then it fills in the whole graph after the path is finished.

这篇关于在画布上填充多边形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆