我正在尝试使用矩形和路径线为网页制作可视化图形。这一切都已完成,现在我想为顶部的一种颜色着色,而另一种颜色则是另一种颜色。我尝试将整个东西变成红色并用绿色覆盖底部(我知道可怕的组合,但它们仅用于测试目的)。它使整个东西变红,但我看不到任何绿色。 所以我的问题是,我怎样才能在底部的颜色与顶部不同?
</head>
<body>
<canvas id="myCanvas" width="600" height="600" style="border:1px solid #D3D3D3;">Your browser does not support the HTML5 canvas tag. </canvas>
<script>
var theCanvas=document.getElementById("myCanvas");
var theContext=theCanvas.getContext("2d");
var rectangle=theCanvas.getContext("2d");
var sales = new Array();
sales[0] = 52;
sales[1] = 48;
sales[2] = 74;
sales[3] = 31;
sales[4] = 47;
sales[5] = 25;
sales[6] = 67;
sales[7] = 78;
sales[8] = 45;
sales[9] = 75;
sales[10] = 85;
var scalar = 10;
var width = 10;
var height = 10;
var spacing = 10
var y = height * scalar;
rectangle.rect(0, 0, (width * scalar), y);
rectangle.fillStyle="red";
rectangle.fill();
rectangle.stroke();
theContext.beginPath();
theContext.moveTo(0, y);
theContext.lineTo(0, (y - sales[0]));
theContext.stroke();
for(var i = -1; i < sales.length; ++i)
{
theContext.moveTo((spacing * i), (y - sales[i]));
theContext.lineTo(spacing * (i + 1), (y - sales[i + 1]));
theContext.stroke();
}
theContext.moveTo((width * scalar), (y - sales[10]));
theContext.lineTo((width * scalar), y);
theContext.stroke();
theContext.moveTo((width * scalar), y);
theContext.lineTo(0, y);
theContext.stroke();
theContext.moveTo(0, y);
theContext.lineTo(0, (y - sales[0]));
theContext.closePath();
theContext.fillStyle="green";//doesn't seem to work!
theContext.fill();
theContext.stroke();
</script>
</body>
答案 0 :(得分:1)
代码正在分解多边形,因为它使用了太多moveTo()
。如果你打破了路径,就不会有任何东西需要填充,因为只剩下不连续的线。
尝试将它们排除在外:
<强> Fiddle 强>
theContext.beginPath();
theContext.moveTo(0, y);
theContext.lineTo(0, (y - sales[0]));
//theContext.stroke();
for(var i = -1; i < sales.length; ++i)
{
//theContext.moveTo((spacing * i), (y - sales[i]));
theContext.lineTo(spacing * (i + 1), (y - sales[i + 1]));
//theContext.stroke();
}
//theContext.moveTo((width * scalar), (y - sales[10]));
theContext.lineTo((width * scalar), y);
theContext.stroke();
//theContext.moveTo((width * scalar), y);
theContext.lineTo(0, y);
//theContext.stroke();
//theContext.moveTo(0, y);
theContext.lineTo(0, (y - sales[0]));
theContext.closePath();
theContext.fillStyle="green"; //works!
theContext.fill();
theContext.stroke();
或清理:
theContext.beginPath();
theContext.moveTo(0, y);
theContext.lineTo(0, (y - sales[0]));
for(var i = -1; i < sales.length; ++i) {
theContext.lineTo(spacing * (i + 1), (y - sales[i + 1]));
}
theContext.lineTo((width * scalar), y);
theContext.stroke();
theContext.lineTo(0, y);
theContext.lineTo(0, (y - sales[0]));
theContext.closePath();
theContext.fillStyle="green"; //works!
theContext.fill();
theContext.stroke();