2016-05-20 9 views
1
function loadMain(){ 
     background.src = "background.png" 
     button.src = "button.png" 
    } 

function drawMain(){ 
    ctx.drawImage(background, 0, 0, canvas.width, canvas.height); 

    ctx.drawImage(button, 100, 100 , canvas.width/10, canvas.height/10); 
} 

この方法は完全にロードしない、 私の質問は: 私のマウスは、そのボタン画像の上にある場合、どのように私は、画像をbutton2.pngする変更できますか? ありがとうJavascriptを、キャンバスのマウスオーバー

+0

限り、DOMイベントは要素にのみ追加できます。ここはキャンバスです。だから、あなたがそれらのいずれかの上にmouseoverイベントを持たせたいならば、マウスがそれらの1つの上にあるなら手動で計算しなければならないでしょう。代わりにsvgを使用することもできます。これがオプションの場合、cos svgはDOMツリーを作成するので、イベントを各svg要素に追加できます。 – sielakos

+0

**仮定:** button.pngとbutton2.pngは完全にロードされていて、同じサイズです... ** 1。** mousemoveイベントを聞きます。 ** 2。**マウスがボタン上にある場合のヒットテスト: 'mouseX> button.x && mouseX button.y && mouseY markE

答えて

1

ここでは、どのように長方形で簡単な例を書いたのですか。

const c = document.getElementById("canvas"); 
const ctx = c.getContext("2d"); 
const msg = document.getElementById("msg"); 
const locations = [ 
    {x: 10, y: 10, width: 40, height: 40, title: "first", color: "red"}, 
    {x: 50, y: 60, width: 30, height: 30, title: "second", color: "blue"}, 
    {x: 30, y: 160, width: 60, height: 60, title: "third", color: "green"}, 
    {x: 20, y: 150, width: 40, height: 40, title: "fourth", color: "#ff40A0"} 
]; 

locations.forEach(({x, y, width, height, color}) => { 
    ctx.fillStyle = color; 
    ctx.fillRect(x, y, width, height); 
}); 

c.addEventListener('mousemove', (event) => { 
    const {layerX, layerY} = event; 

    const titles = locations 
    .filter(({x, y, width, height}) => { 
     return layerX >= x && layerX <= x + width 
     && layerY >= y && layerY <= y + height; 
    }) 
    .map(({title}) => title); 

    msg.innerHTML = `x: ${layerX}, y: ${layerY}, 
     titles: ${titles.join(', ')}`; 
}); 

作業フィドル:https://jsfiddle.net/mmzr6tgo/

基本的な考え方は、canvas要素の「のMouseMove」イベントに新しいイベントリスナーを追加して、キャンバスでのマウスの位置としてlayerXとlayerYを使用することです。次に、マウスが矩形領域内にあるかどうかをチェックするだけです。これは簡単な条件です。

関連する問題