首页 > 求助,关于cancas画六边形!!!!!!

求助,关于cancas画六边形!!!!!!

drawStart(ctx, 150, 300, 400, 400);

function drawStart(ctx, r, R, x, y){
    ctx.beginPath();

    for(var i = 0; i < 5; i++){
        ctx.lineTo(Math.cos((18 + i * 72) / 180 * Math.PI) * R + x, 
            -Math.sin((18 + i * 72) / 180 * Math.PI) * R + y);

        ctx.lineTo(Math.cos((54 + i * 72) / 180 * Math.PI) * r + x, 
            -Math.sin((54 + i * 72) / 180 * Math.PI) * r + y);
    }

    ctx.closePath();
    ctx.stroke();
}

上面是画5角形的代码,请问画正6边行怎么改?


    /**
     * 画个6边形
     * @param ctx 画布上下文
     * @param r 半径,也就是6边形的边长
     * @param x 中心点x坐标
     * @param y 中心点y坐标
     * @param rotate 旋转角度
     */
    function drawStart6(ctx, r, x, y,rotate){
        ctx.save(); // save the default state
        ctx.translate(x,y);
        ctx.rotate(rotate);
        ctx.beginPath();
        for(var i = 0; i < 6; i++){
            ctx.lineTo(Math.cos((i*60)/180*Math.PI)*r,

                    Math.sin((i*60)/180*Math.PI)*r);
        }

        ctx.closePath();
        ctx.stroke();
        ctx.restore(); // restore to the default state
    }

其实正六边形应该算比较容易得到的,运用勾股定理就能得到相应的坐标
骚味改一下原先的代码就好了,可以参考下

var canvas=document.querySelector('#canvas');
canvas.width=800;
canvas.height=800;
var ctx = canvas.getContext('2d');
drawStart(ctx, 100,100,100);

function drawStart(ctx, r, x, y){
    ctx.beginPath();
    for(var i = 0; i < 6; i++){
        ctx.lineTo(Math.cos((i*60) / 180 * Math.PI) * r + x, 
        -Math.sin((i*60) / 180 * Math.PI) * r + y);
    }
    ctx.closePath();
    ctx.stroke();
}

把canvas当成一个坐标轴,拿出各个点的坐标就行了

【热门文章】
【热门文章】