保存在变量/ object-HTML5中在画布上绘制的图像的坐标

时间:2015-04-20 10:38:28

标签: javascript html5 canvas

我需要获取最后绘制的形状的坐标,以便能够应用缩放,旋转等变换。这是我用来绘制形状的代码的一部分:

function drawPolygon(position, sides, angle) {
var coordinates = [],
    radius = Math.sqrt(Math.pow((dragStartLocation.x - position.x), 2) + Math.pow((dragStartLocation.y - position.y), 2)),
    index = 0;

for (index = 0; index < sides; index++) {
    coordinates.push({x: dragStartLocation.x + radius * Math.cos(angle), y: dragStartLocation.y - radius * Math.sin(angle)});
    angle += (2 * Math.PI) / sides;
}

context.beginPath();
context.moveTo(coordinates[0].x, coordinates[0].y);
for (index = 1; index < sides; index++) {
    context.lineTo(coordinates[index].x, coordinates[index].y);
}

context.closePath();
context.stroke();
context.strokeStyle = strokeColor.value;

}

如何保存坐标供以后使用?任何帮助将不胜感激。感谢。

1 个答案:

答案 0 :(得分:1)

我建议做OOP之类的。不知道你的目标是什么,但我认为会有更多的形状,你可以存储在像对象这样的数组中。

另外我认为你是通过使用dragStart和dragEnd来绘制它们的。您想通过传递这些值来创建Polygon对象。

function Polygon(dragStartLocation, dragEndLocation, sides, angle) {

    { // init
        this.coordinates = [];
        this.radius = Math.sqrt(Math.pow((dragStartLocation.x - dragEndLocation.x), 2) + Math.pow((dragStartLocation.y - dragEndLocation.y), 2));
        this.strokeColor = {value: "#000000"}; // maybe also change color of the stroke

        for(index = 0; index < sides; index++) {
            this.coordinates.push({x: dragStartLocation.x + this.radius * Math.cos(angle), y: dragStartLocation.y - this.radius * Math.sin(angle)});
            angle += (2 * Math.PI) / sides;
        }
    }

    this.render = function() {
        context.beginPath();
        context.moveTo(this.coordinates[0].x, this.coordinates[0].y);
        for (index = 1; index < sides; index++) {
            context.lineTo(this.coordinates[index].x, this.coordinates[index].y);
        }

        context.closePath();
        context.strokeStyle = this.strokeColor.value;
        context.stroke();
    }
}

您可以在拖动停止时创建这些对象。例如,当您从(100,100)开始拖动并在(200, 200)结束时。 Polygon的中点为(100, 100)

new Polygon({x: 100, y: 100}, {x: 200, y: 200}, 8, 1);

然后您可以将其存储在变量或数组中。

var list = new Array(
    new Polygon({x: 100, y: 100}, {x: 200, y: 200}, 8, 1), 
    new Polygon({x: 100, y: 100}, {x: 300, y: 300}, 12, 1)
);

之后你可以轻松地绘制它们:

for(var i = 0; i < list.length; i++) {
    list[i].render();
}

这是您访问对象字段的方法。

list[i].coordinates;

但是当你还想翻译,缩放和旋转时,你可能想要存储一些其他字段,并可能计算相对于一个点的坐标。然后转换会更容易。

相关问题