简体   繁体   English

使用HTML5 / Javascript在画布上绘制圆

[英]Drawing a circle on a canvas with HTML5/Javascript

I'm having an issue at the moment with adding a circle to a canvas. 我在将圆圈添加到画布上时遇到问题。 I am required to make a graph. 我需要画一个图。 I have added the x and y axis' to the canvas and need to add circles to act as points on the graph. 我已将x和y轴添加到画布上,需要添加圆圈以充当图形上的点。

Code so far: 到目前为止的代码:

<!DOCTYPE html>
<html>  

<head> 
    <link rel="stylesheet" type="text/css" href="css.css">
</head>

<body onload="drawGraph()" >
    <div id="main">
        <canvas id="theCanvas" width="1100" height="400"></canvas>
    </div>
</body>

</html>

<script type="text/javascript">

function drawGraph () {

//Access the canvas using the ID & set the context:
var a = document.getElementById("theCanvas");
var context = a.getContext("2d");


context.translate(0.5, 0.5);
context.fillStyle = "black";
context.strokeStyle = "black";
context.lineWidth = 3;

//Draw Y Axis:
context.moveTo(50,50);
context.lineTo(50,325);
context.stroke();

//Draw X Axis:
context.moveTo(49,325);
context.lineTo(980,325);
context.stroke();

//"Draw" text for the days of the week on the canvas:
context.font = "15px Arial";
context.fillText("Monday",60,360);
context.fillText("Tuesday",200,360);
context.fillText("Wednesday",340,360);
context.fillText("Thursday",500,360);
context.fillText("Friday",640,360);
context.fillText("Saturday",780,360);
context.fillText("Sunday",920,360);
context.strokeText();


}
</script>

I have tried drawing a circle with the arc method with something like this: 我尝试用arc方法绘制一个圆形,如下所示:

context.beginPath();
context.arc(50,325,20,0,2*Math.PI);
context.stroke();

which doesn't make anything appear on my canvas. 没有任何东西出现在我的画布上。

As far as I can establish online, this is the standard way to do this. 据我所知,这是实现此目的的标准方法。

Am I doing something wrong in this case? 我在这种情况下做错了吗?

You are missing a last argument, a Boolean indicating if the angle should be calculated counterclockwise or clockwise: 您缺少最后一个参数,一个布尔值,指示是否应逆时针或顺时针计算角度:

context.arc(50,325,20,0,2*Math.PI,false); context.arc(50,325,20,0,2 * Math.PI,false);

There is missing arguments for the strokeText method: strokeText方法缺少参数:

context.strokeText();

should be: 应该:

context.strokeText(txt, x, y);

Since they are missing the script will fail and stop not executing anything after it: 由于缺少脚本,因此脚本将失败并停止执行以下操作:
A demo fiddle 演示小提琴

fillText() and strokeText() does not add to the path however, so you need to draw the same text again if you want an outline of it on top. fillText()strokeText()不会添加到路径中,因此,如果要在其顶部放置轮廓,则需要再次绘制相同的文本。

Besides from that the arc is correct as you do it. 除此之外,您所做的arc是正确的。 You could add a closePath() before stroking it though. 您可以在抚摸它之前添加一个closePath()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM