如何获取点击元素的位置和ID以更改颜色并在其上画线
How to get clicked element's position and id to change color and draw lines on it
我正在开发一个基本的 window 框架配置器。我在下面的功能中拆分了眼镜。我想在单击时更改颜色并获取单击玻璃的位置以绘制打开方向线。
我试图理解并实施 Lavrton 的方法(https://codesandbox.io/s/0xj7zml2zl?file=/src/index.js),但我无法成功。
function glassDraw(piece, frameWidth, frameHeight) {
var glassGroup = new Konva.Group();
for (i = 0; i <piece; i++) {
var glass = new Konva.Rect({
name: 'Rect',
x: padding + (frameWidth / piece) * i,
y: padding,
width: frameWidth / piece,
height: frameHeight - padding * 2,
fill: 'lightblue',
id: 'glass'+i,
});
glassGroup.add(glass);
}
glassGroup.find("Rect").on('click', function (e) {
// get id of the cube i drag
var clickedId = e.target.attrs.id;
$('#theId').html(clickedId);
})
return glassGroup;
}
当我使用带有 konva 元素 ("glass"+i) id 的 getelementbyid 方法时,它 returns 为空。我想我需要成为一个 konva 元素。
您必须为所有矩形创建点击侦听器。
for (let rect of glassGroup.children) {
<pre><code> rect.on('click', () => {
console.log(rect.x(), rect.y()); // current position of the object
console.log(rect.id()); // log id of the object
rect.fill('green'); // set color to green
layer.batchDraw(); // update layer (batchDraw just for better performance .draw() would work to)
})
}
确保在更改某些内容后始终通过调用 stage.draw() 或 layer.draw()(或 batchDraw() 以获得更好的性能)来更新舞台,否则您的舞台将不会显示任何内容你所做的。
如果此代码无法正常工作,请随时询问。
祝你有愉快的一天。
我正在开发一个基本的 window 框架配置器。我在下面的功能中拆分了眼镜。我想在单击时更改颜色并获取单击玻璃的位置以绘制打开方向线。 我试图理解并实施 Lavrton 的方法(https://codesandbox.io/s/0xj7zml2zl?file=/src/index.js),但我无法成功。
function glassDraw(piece, frameWidth, frameHeight) {
var glassGroup = new Konva.Group();
for (i = 0; i <piece; i++) {
var glass = new Konva.Rect({
name: 'Rect',
x: padding + (frameWidth / piece) * i,
y: padding,
width: frameWidth / piece,
height: frameHeight - padding * 2,
fill: 'lightblue',
id: 'glass'+i,
});
glassGroup.add(glass);
}
glassGroup.find("Rect").on('click', function (e) {
// get id of the cube i drag
var clickedId = e.target.attrs.id;
$('#theId').html(clickedId);
})
return glassGroup;
}
当我使用带有 konva 元素 ("glass"+i) id 的 getelementbyid 方法时,它 returns 为空。我想我需要成为一个 konva 元素。
您必须为所有矩形创建点击侦听器。
for (let rect of glassGroup.children) {
<pre><code> rect.on('click', () => {
console.log(rect.x(), rect.y()); // current position of the object
console.log(rect.id()); // log id of the object
rect.fill('green'); // set color to green
layer.batchDraw(); // update layer (batchDraw just for better performance .draw() would work to)
})
}
确保在更改某些内容后始终通过调用 stage.draw() 或 layer.draw()(或 batchDraw() 以获得更好的性能)来更新舞台,否则您的舞台将不会显示任何内容你所做的。
如果此代码无法正常工作,请随时询问。
祝你有愉快的一天。