1 回答

TA貢獻(xiàn)2021條經(jīng)驗(yàn) 獲得超8個(gè)贊
這是一個(gè)在鼠標(biāo)下旋轉(zhuǎn)矩形的簡(jiǎn)單函數(shù),無(wú)需使用 konva offset()。我使用補(bǔ)間來(lái)應(yīng)用移動(dòng),但如果您更喜歡在沒(méi)有補(bǔ)間的情況下使用它,只需應(yīng)用 rect.rotate() 然后應(yīng)用 newPos x & y 作為位置。
編輯:OP指出,如果您單擊,在矩形完成動(dòng)畫時(shí)按住鼠標(biāo),然后拖動(dòng),則矩形會(huì)跳開。是什么賦予了 ?好吧,當(dāng) mousedown 事件運(yùn)行時(shí),Konva 會(huì)記錄形狀在其內(nèi)部拖動(dòng)功能中的初始位置。然后當(dāng)我們開始實(shí)際拖動(dòng)鼠標(biāo)時(shí),Konva 會(huì)盡職盡責(zé)地在它計(jì)算出的位置重新繪制形狀?,F(xiàn)在,“我們”知道我們將形狀移入了代碼,但我們沒(méi)有讓 Konva 參與我們的詭計(jì)。
解決方法是調(diào)用
rect.stopDrag();
rect.startDrag();
新位置確定后立即進(jìn)行。因?yàn)槲沂褂玫氖茄a(bǔ)間,所以我在其中一個(gè)補(bǔ)間的 onFinish() 回調(diào)函數(shù)中執(zhí)行此操作 - 如果您應(yīng)用多個(gè)補(bǔ)間,您將希望確保它是最終補(bǔ)間。我僥幸逃脫,因?yàn)槲业难a(bǔ)間在同一時(shí)期運(yùn)行。如果您不使用補(bǔ)間,只需在對(duì)形狀應(yīng)用最后一個(gè) rotate() 或 position() 調(diào)用時(shí)立即調(diào)用上述方法。
function rotateUnderMouse(){
// Get the stage position of the mouse
var mousePos = stage.getPointerPosition();
// get the stage position of the mouse
var shapePos = rect.position();
// compute the vector for the difference
var rel = {x: mousePos.x - shapePos.x, y: mousePos.y - shapePos.y}
// Now apply the rotation
angle = angle + 90;
// and reposition the shape to keep the same point in the shape under the mouse
var newPos = ({x: mousePos.x + rel.y , y: mousePos.y - rel.x})
// Just for fun, a tween to apply the move: See https://konvajs.org/docs/tweens/Linear_Easing.html
var tween1 = new Konva.Tween({
node: rect,
duration: 0.25,
x: newPos.x,
y: newPos.y,
easing: Konva.Easings.Linear,
onFinish: function() { rect.stopDrag(); rect.startDrag();}
});
// and a tween to apply the rotation
tween2 = new Konva.Tween({
node: rect,
duration: 0.25,
rotation: angle,
easing: Konva.Easings.Linear
});
tween2.play();
tween1.play();
}
function setup() {
// Set up a stage and a shape
stage = new Konva.Stage({
container: 'canvas-container',
width: 650,
height: 300
});
layer = new Konva.Layer();
stage.add(layer);
newPos = {x: 80, y: 40};
rect = new Konva.Rect({
width: 140, height: 50, x: newPos.x, y: newPos.y, draggable: true, stroke: 'cyan', fill: 'cyan'
})
layer.add(rect);
stage.draw()
rect.on('mousedown', function(){
rotateUnderMouse()
})
}
var stage, layer, rect, angle = 0;
setup()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/konva/4.0.13/konva.js"></script>
<p>Click the rectangle - it will rotate under the mouse.</p>
<div id="canvas-container"></div>
添加回答
舉報(bào)