用单个arc()函数调用绘制pacman形状?

时间:2012-12-30 18:32:35

标签: html5 canvas html5-canvas

根据我目前对arc()函数如何工作的理解,试图找出为什么我不能绘制pacman形状。

当我在Chrome / Firefox中尝试以下代码时,它会绘制一个完整的圆圈,这不是我所期望的。我怀疑它可能与非零缠绕规则有关?我的猜测是-45正在内部归一化,导致产生的角度扫描变为CCW而不是CW。但是当我通过将最终的arg更改为CCW来测试该假设时,Chrome中没有任何变化(但是FF的行为不同之处在于没有绘制任何东西)

// draw pacman shape
ctx.arc(200,200,50, -45 * DEGREES, 45 * DEGREES, false);
ctx.stroke();

完整示例: http://pastebin.com/2ZkJXgJU

4 个答案:

答案 0 :(得分:3)

我知道这是一个老问题,已经得到了回答,但我认为有一种更简单的方法可以用一个弧形绘制pac-man。

// An arc with an opening at the right for the mouth
ctx.beginPath();
ctx.arc(100, 100, 50, 0.2 * Math.PI, 1.8 * Math.PI, false);

// The mouth
// A line from the end of the arc to the centre
ctx.lineTo(100, 100);

// A line from the centre of the arc to the start
ctx.closePath();

// Fill the pacman shape with yellow
ctx.fillStyle = "yellow";
ctx.fill();

// Draw the black outline (optional)
ctx.stroke();

// Draw the eye
ctx.beginPath();
ctx.arc(100, 75, 10, 0, 2 * Math.PI, false);
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.fill();

接受的答案可行,但它使用了两个半圆而不是一个圆弧。此方法还为您提供绘制轮廓的选项。

答案 1 :(得分:2)

这就是你要找的东西:

ctx.beginPath();
ctx.arc(100, 100, 50, 0.25 * Math.PI, 1.25 * Math.PI, false);
ctx.fillStyle = "rgb(255, 255, 0)";
ctx.fill();
ctx.beginPath();
ctx.arc(100, 100, 50, 0.75 * Math.PI, 1.75 * Math.PI, false);
ctx.fill();
ctx.beginPath();
ctx.arc(100, 75, 10, 0, 2 * Math.PI, false);
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.fill();

来源:http://simeonvisser.hubpages.com/hub/HTML5-Tutorial-Drawing-Circles-and-Arcs

答案 2 :(得分:2)

你的第四和第五个论点是错误的,它们的范围从-Math.PI到Math.PI,而不是度数。

我曾经制作的一个技巧#pacman'像形状一样通过将笔划的大小设置为等于圆的半径

ctx.lineWidth = 50;
ctx.arc(200,200,50,Math.PI*2.1,Math.PI*1.7, false);
ctx.stroke();

请参阅:http://jsfiddle.net/8JaLY/2/

答案 3 :(得分:0)

请参阅https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/beginPath以了解什么是PATH

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

var centerX = 100;
var centerY = 100;
var radius = 50; 
ctx.beginPath();
ctx.moveTo(centerX,centerY);
ctx.arc(
  centerX,centerY,radius,
  -Math.PI/4,Math.PI/4, // -45 deg to 45 deg
  true //anticlockwise
 );
ctx.lineTo(centerX,centerY);
ctx.stroke();//border
ctx.fillStyle = "rgb(255, 255, 0)";
ctx.fill();
ctx.closePath();
<canvas id="myCanvas" width="480" height="320"></canvas>