如何在画布上绘制一个简单的五角大楼 [英] How to draw a simple Pentagon in canvas

查看:159
本文介绍了如何在画布上绘制一个简单的五角大楼的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个五边形,我成功创建了五边形.

I want to create a Pentagon, I succeeded in creating such pentagon.

但是我的五边形是不正确的,因为它在表面上不正确.

But my pentagon is not right, because it doesn't stand right on the surface.

我该如何解决?我需要一个简洁的答案,而不仅仅是快速修复.

How can I fix it? I need an elegant answer not just a quick fix.

我还想知道另一件事:

如何仅使用坐标绘制五边形,我是指五边形的5个坐标?

How can I draw a Pentagon using coordinates only, I mean the 5 coordinates of the pentagon?

我想基于五个已知坐标(v1,v2..v5)绘制一个五边形 而且没有任何循环,可以在五个点之间画出某种路径.

I want to draw a pentagon based on five known cordinates(v1,v2..v5) and without any loop,to draw some kind of path between five points.

$(function(){
var canvas=document.getElementById("canvas");
var cxt=canvas.getContext("2d");
    // hexagon
    var numberOfSides = 5,
        size = 100,
        Xcenter = 150,
        Ycenter = 150;

    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();
  });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width=650 height=500></canvas>

推荐答案

有趣的问题,您可以移动sin/cos值,使底线水平对齐:

Interesting question, you can shift the sin/cos values so the bottom line aligns horizontally:

$(function(){
   var canvas=document.getElementById("canvas");
   var cxt=canvas.getContext("2d");
    // hexagon
    var numberOfSides = 5,
        size = 100,
        Xcenter = 150,
        Ycenter = 150,
        step  = 2 * Math.PI / numberOfSides,//Precalculate step value
        shift = (Math.PI / 180.0) * -18;//Quick fix ;)

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

    for (var i = 0; i <= numberOfSides;i++) {
    	var curStep = i * step + shift;
        cxt.lineTo (Xcenter + size * Math.cos(curStep), Ycenter + size * Math.sin(curStep));
    }

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

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width=650 height=500></canvas>

这篇关于如何在画布上绘制一个简单的五角大楼的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆