缩放 Matter.js canvas 打破鼠标拖动
Scaling Matter.js canvas breaks mouse drag
我的问题是:
我使用 Matter.js 在 canvas 上创建了一个可拖动对象。但是,当我缩放 canvas 时,我的鼠标点击不再拖动对象,因为点击因缩放而计算错误。 Matter.js 仍然认为 canvas 没有缩放。所以我必须在对象旁边单击才能真正拖动它。而且我缩放的越多,我必须从对象上点击越多。我需要做什么才能更正 Matter.js canvas 已缩放?
<body>
<script>
let Engine = Matter.Engine,
Render = Matter.Render,
World = Matter.World,
Bodies = Matter.Bodies;
let engine = Engine.create();
let render = Render.create({
element: document.body,
engine: engine
});
Engine.run(engine);
Render.run(render);
let floor = Bodies.rectangle(0, 500, 600, 10, { isStatic: true });
let ball = Bodies.circle(200, 10, 40);
World.add(engine.world, [ball, floor]);
render.canvas.width = 1000;
render.canvas.height = 800;
render.canvas.style.transformOrigin = '0 0';
render.canvas.style.transform = 'scale(.8)';
let world = engine.world;
let Mouse = Matter.Mouse;
let MouseConstraint = Matter.MouseConstraint;
let mouse = Mouse.create(render.canvas);
let mouseConstraint = MouseConstraint.create(engine, { mouse: mouse });
World.add(world, mouseConstraint);
render.mouse = mouse;
</script>
</body>
亲切的问候,Slawek
感谢 ggorlen,答案是:
使用Matter.Mouse.setScale(鼠标、缩放);
您需要提供正确的比例尺,但您怎么知道只有初始比例尺用于缩放 canvas?
公式如下:
set scale(scale){
let mouseScale = 1 + (1 / (scale / (1 - scale)))
this.Mouse.setScale(this.mouse, {x: mouseScale, y: mouseScale});
}
我的问题是:
我使用 Matter.js 在 canvas 上创建了一个可拖动对象。但是,当我缩放 canvas 时,我的鼠标点击不再拖动对象,因为点击因缩放而计算错误。 Matter.js 仍然认为 canvas 没有缩放。所以我必须在对象旁边单击才能真正拖动它。而且我缩放的越多,我必须从对象上点击越多。我需要做什么才能更正 Matter.js canvas 已缩放?
<body>
<script>
let Engine = Matter.Engine,
Render = Matter.Render,
World = Matter.World,
Bodies = Matter.Bodies;
let engine = Engine.create();
let render = Render.create({
element: document.body,
engine: engine
});
Engine.run(engine);
Render.run(render);
let floor = Bodies.rectangle(0, 500, 600, 10, { isStatic: true });
let ball = Bodies.circle(200, 10, 40);
World.add(engine.world, [ball, floor]);
render.canvas.width = 1000;
render.canvas.height = 800;
render.canvas.style.transformOrigin = '0 0';
render.canvas.style.transform = 'scale(.8)';
let world = engine.world;
let Mouse = Matter.Mouse;
let MouseConstraint = Matter.MouseConstraint;
let mouse = Mouse.create(render.canvas);
let mouseConstraint = MouseConstraint.create(engine, { mouse: mouse });
World.add(world, mouseConstraint);
render.mouse = mouse;
</script>
</body>
亲切的问候,Slawek
感谢 ggorlen,答案是:
使用Matter.Mouse.setScale(鼠标、缩放);
您需要提供正确的比例尺,但您怎么知道只有初始比例尺用于缩放 canvas? 公式如下:
set scale(scale){
let mouseScale = 1 + (1 / (scale / (1 - scale)))
this.Mouse.setScale(this.mouse, {x: mouseScale, y: mouseScale});
}