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

曼尼莎·辛格·萨努(Manisha Singh Sanoo)

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

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;

}

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

水母男人

我建议这样做像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)多边形的中点将为(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;

但是,当您还想要平移,缩放和旋转时,您可能想要存储其他字段,并可能计算相对于一个点的坐标。这样,转换将变得更加容易。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章