我在大学做一个练习,要求在这里使用openGraphics,canvas绘制图形。

我快到终点了。唯一无法正常工作的是矩形,它们起着列的作用,是下降而不是上升。

看起来像这样:
javascript - 用Javascript绘制天气数据图-LMLPHP

但是应该看起来像这样:

javascript - 用Javascript绘制天气数据图-LMLPHP

代码:

var canvas;
canvas = openGraphics();

canvas.setFont("TIMES", "13px", Font.BOLD);
canvas.drawString("Weather Data: Bradford 2015", 5, 10);
canvas.drawString("Sunshine (in hours)", 5, 30);
canvas.setFont("TIMES", "12px", Font.PLAIN);

var i = 0;
var k = 0;
var month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
while(i < 12) {
var hours = prompt("Type amount of sunshine hours for " + month[k]);

canvas.setColor("pink");
canvas.fillRect(20+30*i, 280, 30, hours);
canvas.setColor("black");
canvas.drawRect(20+30*i, 280, 30, hours);


i += 1;
k += 1;

}

canvas.setStroke("3");
canvas.drawLine(20, 60, 20, 280);
canvas.drawLine(20, 280, 380, 280);

canvas.setFont("TIMES", "13px", Font.BOLD);
canvas.drawString("0", 5, 270);
canvas.drawString("45", 5, 225);
canvas.drawString("90", 5, 180);
canvas.drawString("135", 0, 135);
canvas.drawString("180", 0, 90);
canvas.drawString("225", 0, 55);
canvas.drawString("J", 35, 285);
canvas.drawString("F", 65, 285);
canvas.drawString("M", 95, 285);
canvas.drawString("A", 125, 285);
canvas.drawString("M", 155, 285);
canvas.drawString("J", 185, 285);
canvas.drawString("J", 215, 285);
canvas.drawString("A", 245, 285);
canvas.drawString("S", 275, 285);
canvas.drawString("O", 305, 285);
canvas.drawString("N", 335, 285);
canvas.drawString("D", 365, 285);


canvas.paint();

最佳答案

矩形将从代表其左上角的点开始绘制。那一点是canvas.fillRect的前两个参数。

所以我看到:canvas.fillRect(20+30*i, 280, 30, hours);,其中每个矩形的起始y坐标都相同(280)。这意味着它将从280中提取hours数量。所以,是的,这将使所有矩形下降并看起来与您的预期相反。

尝试从第二个参数中的280-hours开始。

因此:canvas.fillRect(20+30*i, 280-hours, 30, hours);

关于javascript - 用Javascript绘制天气数据图,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36899846/

10-13 00:35