簡體   English   中英

Fabric JS 使用鼠標:懸停在動畫對象上

[英]Fabric JS using mouse:over on an animating object

我可以為一個對象設置動畫,然后添加一個mouse:over事件。

 var canvas = new fabric.Canvas('c'); var x1 = 5; var y1 = 5; var x2 = 100; var y2 = 100; var rect = new fabric.Rect({ width: 10, height: 10, left: x1, top: y1, stroke: '#000', strokeWidth: 2, fill: '#faa', selectable: false }); canvas.add(rect); rect.animate({ 'left': x2, 'top': y2 }, { duration: 10000, onChange: canvas.renderAll.bind(canvas), onComplete: function() { } }); canvas.on('mouse:over', function (e) { console.log('mouseover'); });
 <canvas id="c"></canvas> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.3/fabric.min.js"></script>

但是mouse:over事件繼續從矩形的原始位置觸發。 動畫完成后, mouse:over事件將再次作用於動畫對象。

是否可以在對象移動/動畫時觸發mouse:over事件?

我無法找出內置方式。 您可能希望將此作為問題提交。 與此同時,我想我有一個可用的解決方法:

 // Setup var canvas = new fabric.Canvas('c'); var x1 = 5; var y1 = 5; var x2 = 100; var y2 = 100; var rectWidth = 10; var rectHeight = 10; var rect = new fabric.Rect({ width: rectWidth, height: rectHeight, left: x1, top: y1, stroke: '#000', strokeWidth: 2, fill: '#faa', selectable: false }); canvas.add(rect); rect.animate({ 'left': x2, 'top': y2 }, { duration: 10000, onChange: canvas.renderAll.bind(canvas), onComplete: function() { } }); // http://stackoverflow.com/questions/17130395/real-mouse-position-in-canvas function getMousePos(canvas, evt) { var rect = canvas.getBoundingClientRect(), // abs. size of element scaleX = canvas.width / rect.width, // relationship bitmap vs. element for X scaleY = canvas.height / rect.height; // relationship bitmap vs. element for Y return { x: (evt.clientX - rect.left) * scaleX, // scale mouse coordinates after they have y: (evt.clientY - rect.top) * scaleY // been adjusted to be relative to element } } // The important stuff canvas.on('mouse:move', function (o) { var pos = getMousePos(canvas.getElement(), oe); // Do math to figure out if the mouse move was inside the the object. For a Rect: if ( pos.x >= rect.left && pos.x <= rect.left + rectWidth && pos.y >= rect.top && pos.y <= rect.top + rectHeight ) { console.log('mouseover'); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.3/fabric.min.js"></script> <canvas id="c"></canvas>

本質上,我聽mouse:move 每次鼠標移動時,我都會獲取光標坐標並檢查它是否在形狀內。

現在,它被硬編碼為僅適用於Rect ,但也許您可以引入一個類似isInside(object, pos)的函數isInside(object, pos)它返回一個boolean ,在那里您可以檢查object是什么類型並基於此做出決定。

我意識到這個話題很老了,但我剛剛遇到了同樣的問題。

經過一番折騰,結果發現在對象移動后調用setCoords()將更新內部狀態,以便mouseover再次正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM