【问题标题】:Error drawing polygon on HTML5 canvas在 HTML5 画布上绘制多边形时出错
【发布时间】:2013-07-26 07:45:02
【问题描述】:

我有以下代码可以在单击按钮时在 HTML5 画布上绘制任何多边形。用户提供半径、边、x 和 y 坐标。应使用边绘制任何正多边形。首先我们使用 moveTo() 移动到周边,然后根据边使用 lineTo() 绘制线条。

js.js

function drawPolygon() {
var numberOfSides = prompt("Enter number of sides");
var Xcenter = prompt("Enter x");
var Ycenter = prompt("Enter y");
var size = prompt("Enter radius");

var con=document.getElementById("myCanvas");
var cxt=con.getContext("2d");

cxt.beginPath();
cxt.moveTo (Xcenter +  size * Math.cos(0), Ycenter +  size *  Math.sin(0));          

for (var i = 1; i <= numberOfSides;i += 1) {
cxt.lineTo (Xcenter + size * Math.cos(i * 2 * Math.PI / numberOfSides), Ycenter + size * Math.sin(i * 2 * Math.PI / numberOfSides));
}

cxt.strokeStyle = "#000000";
cxt.lineWidth = 1;
cxt.stroke();

}
function registerEvents(){ 
var poly = document.getElementById("polygon");
poly.addEventListener( "click", drawPolygon, false); 
}
window.addEventListener('load', registerEvents, false);

提供输入后,画布上不会绘制任何内容。我的代码是错误的吗?

【问题讨论】:

  • 我相信Ycenter + size * Math.sin(0) 会返回一个字符串,不是吗?尝试将parseInt() 应用到您的prompts。

标签: javascript html html5-canvas


【解决方案1】:

您的数学计算有误,因为您没有将输入转换为数值。

例如Ycenter + size * Math.sin(0) 不会返回正确的结果,除非 Ycentersize 是数值。

你可能应该这样做:

var Xcenter = parseFloat(prompt("Enter x"));
var Ycenter = parseFloat(prompt("Enter y"));
var size = parseFloat(prompt("Enter radius"));

【讨论】:

  • 我还有一个问题。所有图纸都位于左上角(默认)。有没有办法控制定位?
  • @dhani,AFAIK,您必须在坐标中考虑到这一点。但我想有些图书馆可以为你做到这一点。
  • 既然您知道左上角 = 0,0,您可以从一开始就轻松 ctx.translate(canvas.width/2, canvas.height/2)。这会将画布的中心设置为 0,0。
【解决方案2】:

这是一个甚至支持顺时针/逆时针绘制的功能,您可以使用非零缠绕规则控制填充。

Here is a full article on how it works and more.

// Defines a path for any regular polygon with the specified number of sides and radius, 
// centered on the provide x and y coordinates.
// optional parameters: startAngle and anticlockwise

function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise) {
  if (sides < 3) return;
  var a = (Math.PI * 2)/sides;
  a = anticlockwise?-a:a;
  ctx.save();
  ctx.translate(x,y);
  ctx.rotate(startAngle);
  ctx.moveTo(radius,0);
  for (var i = 1; i < sides; i++) {
    ctx.lineTo(radius*Math.cos(a*i),radius*Math.sin(a*i));
  }
  ctx.closePath();
  ctx.restore();
}

// Example using the function.
// Define a path in the shape of a pentagon and then fill and stroke it.
context.beginPath();
polygon(context,125,125,100,5,-Math.PI/2);
context.fillStyle="rgba(227,11,93,0.75)";
context.fill();
context.stroke();

【讨论】:

    猜你喜欢
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 2015-01-08
    相关资源
    最近更新 更多