我想编写顶点函数以使用纯JavaScript创建6个顶点的多边形

时间:2018-08-22 07:00:47

标签: javascript html canvas

我希望顶点函数通过使用Brick构造函数的显示方法中创建的点绘制线来创建多边形。

<canvas id="polygon"></canvas>

全局变量

var width;
var height;

矢量对象

    var vector = {
    _x: 0,
    _y: 0,

    create: function(x, y) {
        var obj = Object.create(this);
        obj.init(x, y);
        return obj;
    },

    init: function(x, y) {
        this._x = x;
        this._y = y;
    },

    setX: function(value) {
        this._x = value;
    },
    getX: function() {
        return this._x;
    },
    setY: function(value) {
        this._y = value;
    },
    getY: function() {
        return this._y;
    },
    setLength: function(length) {
        var angle = this.getAngle();
        this._x = Math.cos(angle) * length;
        this._y = Math.sin(angle) * length;
    },
    getLength: function() {
        return Math.sqrt(this._x * this._x + this._y * this._y);
    },
    setAngle: function(angle) {
        var length = this.getLength();
        this._x = Math.cos(angle) * length;
        this._y = Math.sin(angle) * length;
    }
};

这应该使用顶点绘制一条线

function vertex(context, x, y) {
    context.beginPath();
    context.moveTo(x, y);
    context.lineTo(x, y);
    context.stroke();
};

砖构造函数

function Brick(pos, r) {
    this.pos = vector.create(Math.floor(Math.random() * 100 + width -100), 
        Math.floor(Math.random() * 100 + height -100));
    this.total = 6;

    this.display = function(context) {
        context.save();
        context.translate(this.pos.x, this.pos.y);
        context.beginPath();
        for (var i = 0; i < this.total; i++) {
            var angle = map(i, 0, this.total, 0, Math.PI * 2);
            var r = this.r;
            var x = Math.cos(angle);
            var y = Math.sin(angle);
            vertex(context, x, y);
        }
        context.closePath();
        context.restore();
    }
};

这将360度的完整圆除以6点

function map(x, in_min, in_max, out_min, out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

主JavaScript文件

window.onload = function() {
    var canvas = document.getElementById("polygon"),
        context = canvas.getContext("2d"),
        width = canvas.width = window.innerWidth,
        height = canvas.height = window.innerHeight;

    var bricks = [];

    for (var i = 0; i < 20; i++) {
        bricks.push(new Brick());
    }

动画部分

    update();

    function update() {
        context.clearRect(0, 0, width, height);

        for (var j = 0; j < bricks.length; j++) {
            bricks[j].display();
        }

        requestAnimationFrame(update);
    }

}

0 个答案:

没有答案