javascript 如何在 HTML5 画布中绘制带有文本的圆圈
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14539837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to draw circles in HTML5 canvas with text in them
提问by user1779563
Seemed simple enough to draw circles and text in an HTML5 canvas, but I get non-intuitive behavior. The circles get drawn nice and pretty, then the more circles I draw, the oldercircles become more and more octagonal shaped. Very strange to me... Also, the text disappears from the old circles and only appears on the last circle drawn. What's the proper way to do this with canvases?
看起来很简单,可以在 HTML5 画布中绘制圆圈和文本,但我得到了不直观的行为。圆圈画得漂亮漂亮,然后我画的圆圈越多,旧圆圈变得越来越八角形。对我来说很奇怪......此外,文本从旧圆圈中消失,只出现在绘制的最后一个圆圈上。用画布做到这一点的正确方法是什么?
$("#circles_container").on("click", "#circles_canvas", function(event) {
var canvas = document.getElementById('circles_canvas');
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
var w = 16;
var x = event.pageX;
var y = Math.floor(event.pageY-$(this).offset().top);
ctx.fillStyle = "rgb(200,0,0)";
ctx.arc(x, y, w/2, 0, 2 * Math.PI, false);
ctx.fill();
ctx = canvas.getContext("2d");
ctx.font = '8pt Calibri';
ctx.fillStyle = 'white';
ctx.textAlign = 'center';
ctx.fillText('0', x, y+3);
}
});
回答by Denys Séguret
Just add this near the start of your function :
只需在您的功能开始附近添加它:
ctx.beginPath();
You were drawing a path always longer.
你画的路径总是更长。
Demonstration(click on the canvas)
演示(点击画布)

