【问题标题】:Javascript/Canvas: Mouse coordinates don't match after scaling (collision)Javascript/Canvas:缩放后鼠标坐标不匹配(碰撞)
【发布时间】:2017-09-09 20:26:37
【问题描述】:

调整正方形大小后,出现碰撞问题,GIF animation problem,样本https://jsfiddle.net/8jkxdhfv/。我能做些什么?我应该将未转换的鼠标坐标转换为转换的坐标吗?但是怎么做?如何更新碰撞函数中的 x 和 y?

HTML

<canvas id="test" width="480" height="380"></canvas>
<div id="text">Use mouse wheel to change square size</div>

JAVASCRIPT

var ctx = test.getContext('2d');
var obj = { x:100,y: 100,width: 100,height: 100}
var mouse = {x:0, y:0, width:10, height:10};
var zoom = 1;

setInterval(function(){
    ctx.clearRect(0,0,test.width,test.height);
    ctx.save();

    var cx = obj.x+obj.width/2;
    var cy = obj.y+obj.height/2;

    // draw
    ctx.translate(cx, cy);
    ctx.scale(zoom,zoom);
    ctx.translate(-cx,-cy);
    ctx.fillRect(obj.x,obj.y,obj.width,obj.height);
    ctx.restore();

    // check collision
    if(collision(obj,mouse)){
        ctx.fillText("===== COLLISION =====", 110,90);
    }
},1000/60);

function collision(obj1,obj2){  
    if(obj1.x < obj2.x + obj2.width * zoom &&
    (obj1.x + obj1.width * zoom) > obj2.x &&
    obj1.y < obj2.y + obj2.height * zoom &&
    (obj1.height * zoom + obj1.y) > obj2.y){
        return true;
    }
    return false;
}

window.addEventListener('mousewheel', function(e){
    if(e.deltaY>0 && zoom<2){
        zoom+=0.5;
    }

    if(e.deltaY<0 && zoom>0.5){
        zoom-=0.5;
    }
}, false);

window.addEventListener('mousemove', function(e){
    mouse.x = e.pageX;
    mouse.y = e.pageY;

}, false);

【问题讨论】:

    标签: javascript canvas coordinates mouse scaling


    【解决方案1】:

    您正在根据整个窗口而不是画布获取鼠标位置。一些数学,你会得到你想要的。

    test.addEventListener("mousemove", function(evt) {
      var mousePos = getMousePos(test, evt);
      mouse.x = mousePos.x;
      mouse.y = mousePos.y;
    });
    
    function getMousePos(canvas, event) {
      var rect = canvas.getBoundingClientRect();
      return {
        x: event.clientX - rect.left,
        y: event.clientY - rect.top
      };
    }
    

    【讨论】:

    • 感谢您的回答,但我在 css 位置使用:absolute, left:0px;顶部:0px;但是“一些数学”听起来很有趣......;)
    【解决方案2】:

    我已经更新了函数并且它可以工作了:

    function collision(obj1,obj2){
        var eW = (obj1.width-(obj1.width*zoom))/2;
        var eH = (obj1.height-(obj1.height*zoom))/2;
        //console.log(eW);
        if(obj1.x+eW < obj2.x + obj2.width * zoom &&
        (obj1.x + obj1.width * zoom) + eW> obj2.x &&
        obj1.y + eH < obj2.y + obj2.height * zoom &&
        (obj1.height * zoom + obj1.y) + eH > obj2.y){
            return true;
        }
        return false;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-09-13
      • 2019-12-07
      • 2016-01-01
      • 2011-04-06
      • 1970-01-01
      • 2021-11-18
      • 2014-08-27
      • 2017-02-08
      相关资源
      最近更新 更多