2017-04-13 69 views
0

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

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); 

回答

0

我已经更新的功能和它的工作原理:

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; 
} 
0

您是基于整个窗口,不是帆布获得鼠标的位置。有些数学,你会得到你想要的。

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 
    }; 
} 
+0

感谢的答案,但我使用CSS中的位置是:绝对的,左:0像素;顶:0像素;但“有些数学”听起来很有趣......;) – User9213