【发布时间】:2019-01-07 23:40:12
【问题描述】:
我在 Konva 中有两个可拖动的矩形,取自 tutorial。
我的目标是让红色(不可拖动)矩形始终处于蓝色可拖动矩形的平均位置。
我尝试从教程代码中更改它:
box1.on('mouseover', function() {
document.body.style.cursor = 'pointer';
center.x = (box1.x() + box2.x() ) / 2; // added
center.y = (box1.y() + box2.y()) / 2; // added
});
center 是我想保留在中间的红色矩形。
我认为问题在于center.x = (box1.x() + box2.x() ) / 2; 创建了一个新变量,而不是按照我的意愿更改矩形的位置。
我还补充了:
stage.on('contentMousemove', function () {
layer.batchDraw();
});
但还是不行。
如何实时更新中心矩形的x 和y 坐标并在我拖动其他矩形时看到它移动?
可以看出问题的最小示例:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.rawgit.com/konvajs/konva/2.1.7/konva.min.js"></script>
<meta charset="utf-8">
<title>Interactive center of mass simulation</title>
<p>Drag the blue rectangles around, they have mass proportional to their area.
The red rectangle, that reresents the center of mass will move in real time<p>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #F0F0F0;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
var box1 = new Konva.Rect({
x: 100,
y: 100,
width: 50,
height: 50,
fill: '#00D2FF',
stroke: 'black',
strokeWidth: 4,
draggable: true
});
var box2 = new Konva.Rect({
x: 200,
y: 100,
width: 50,
height: 50,
fill: '#00D2FF',
stroke: 'black',
strokeWidth: 4,
draggable: true
});
var center = new Konva.Rect({
x: (box1.x() + box2.x() ) / 2,
y: (box1.y() + box2.y() ) / 2,
width: 50,
height: 50,
fill: '#FF0000',
stroke: 'black',
strokeWidth: 4,
draggable: false
});
box1.on('mouseover', function() {
document.body.style.cursor = 'pointer';
center.x = (box1.x() + box2.x() ) / 2;
center.y = (box1.y() + box2.y()) / 2;
});
box1.on('mouseout', function() {
document.body.style.cursor = 'default';
});
box2.on('mouseover', function() {
document.body.style.cursor = 'pointer';
center.x = (box1.x() + box2.x() ) / 2;
center.y = (box1.y() + box2.y()) / 2;
});
box2.on('mouseout', function() {
document.body.style.cursor = 'default';
});
layer.add(box1);
layer.add(box2);
layer.add(center);
stage.add(layer);
stage.on('contentMousemove', function () {
layer.batchDraw();
});
</script>
</body>
</html>
【问题讨论】:
标签: javascript html animation canvas konvajs