如何在JavaScript中使坐标对象动态

How can I make a Coordinates Object Dynamic in JavaScript?

本文关键字:坐标 对象 动态 JavaScript      更新时间:2023-09-26

我正在使用lines作为Titanium Appcelerator的一个模块来绘制线条。在直线中,您只需要2个具有坐标的对象来绘制直线(起点和终点)。

我想用"touchmove"事件修改起点/终点对象,但我对JavaScript还很陌生,我就是不知道该怎么做。

var lines = require('com.lines'); //<< Import lines module
var attrib = { 
    color:'red',
    touchEnable:true,
    thickness:20
};
var from = {x:20,y:100}; //<< Start Point Object Coordinates
var to = {x:200,y:100}; //<< End POint Object Coordinates
var lineOne = lines.createLine(from, to, attrib); //<<Creates lineOne var with attributes
win.add(lineOne); //Draw the line. 

使用lineOne变量移动整行没有问题,但是正如我所说,我找不到动态修改对象的方法。

谢谢!

更新-在Josiah的建议之后,我成功地修改了"to"变量,但无论如何,这条线都会用原来的"to"值重新绘制。我要么错误地使用了setTo方法,要么我需要其他东西来更新和重新绘制这条线。。

var attrib = {
    color:'red',
    touchEnable:true,
    thickness:20
};
var from = {x:20,y:100}; //Insert touchMoveFunction <<-- Here! 
var to = {x:200,y:100};
var lineOne = lines.createLine(from, to, attrib);
function drawline(e){
    win.add(lineOne);
};
alert(to);
var lineOne = lines.createLine(from,to,attrib);
var buttonPosition = Ti.UI.createButton({
    title:'CLick.Me!',
    bottom:0
});
win.add(buttonPosition);
buttonPosition.addEventListener('click',function(e){
    to = {x:200,y:300};
    lineOne.setTo(to);
    drawline();
    alert(to);
});

只需将touchmove的事件侦听器附加到窗口(或保存行的任何视图容器),然后刷新,或更改行所需的任何内容,这里有一个小示例:

var lineOne = lines.createLine(from, to, attrib);
win.add(lineOne);
win.addEventListener('touchmove', function(e) {
    win.remove(lineOne);
    var touchX = e.x;
    var touchY = e.y;
    var to = {x:touchX,y:touchY}; 
    lineOne = lines.createLine(from, to, attrib);
    // Add a new line
    win.add(lineOne);
});