[英]How to get id by selected item in Fabric.js
I have a canvas and I add a rectangle in it.我有一个画布,并在其中添加了一个矩形。 Each rectangle has its own ID.
每个矩形都有自己的 ID。 How can I get the ID by double clicking on the rectangle on the canvas?
如何通过双击画布上的矩形来获取 ID? It can be either Alert or consolLog.
它可以是 Alert 或 consolLog。
Example: http://fabricjs.com/manage-selection示例: http : //fabricjs.com/manage-selection
You can add your own properties to an object.您可以将自己的属性添加到对象。 For example [1] :
例如[1] :
var rect = new fabric.Rect({
// ...
metaData: {
id: 'myId'
}
});
Then you can get if on select for example:然后你可以得到 if on select 例如:
rect.on('selected', e => {
console.log(canvas.getActiveObject().metaData?.id);
});
Live example:现场示例:
const canvas = new fabric.Canvas('c'); // create a rectangle object const rect = new fabric.Rect({ left: 10, top: 10, fill: 'red', width: 40, height: 40, metaData: { id: 'myId' } }); // add "selected" listener rect.on('selected', e => { console.log(canvas.getActiveObject().metaData?.id); }); // "add" rectangle onto canvas canvas.add(rect);
canvas { border: 1px solid; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.2.0/fabric.min.js" integrity="sha512-Pdu3zoEng2TLwwjnDne3O7zaeWZfEJHU5B63T+zLtME/wg1zfeSH/1wrtOzOC37u2Y1Ki8pTCdKsnbueOlFlMg==" crossorigin="anonymous"></script> <canvas id="c" width="200" height="200"></canvas>
[1] Of course you can also add it as a direct property (without the metaData
) but maybe it will be better to remind you that it's not fabris property but yours [1]当然,您也可以将其添加为直接属性(没有
metaData
),但也许最好提醒您它不是 fabris 属性,而是您的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.