画布绘制对象的鼠标事件

时间:2013-01-29 20:56:32

标签: javascript jquery html5 canvas globalcompositeoperation

我想使用this插件创建基于画布的网站菜单,以创建'乘以'影响。然而,这个以及globalCompositeOperation正在同一个画布中处理ctx对象。 (在上下文混合器中,它使用离屏画布并使用其绘制信息,globalcompoperation混合相同的ctx)。 我想为每个ctx对象创建鼠标事件(悬停和单击),因此每个ctx将导致一个不同的URL。

这是我的测试:

      function draw(){
      var ctx = document.getElementById('canvasOff1').getContext('2d');
      var ctx2 = document.getElementById('canvasReal').getContext('2d');
      var ctx3 = document.getElementById('canvasOff3').getContext('2d');

      // draw circles - each circle should link to different url and has its own focus
      ctx.fillStyle = "#c7302a";
      ctx.beginPath();
      ctx.arc(50,75,35,0,Math.PI*2,true);
      ctx.fill();

      ctx2.fillStyle = "#395797";
      ctx2.beginPath();
      ctx2.arc(100,75,35,0,Math.PI*2,true);
      ctx2.fill();

  ctx3.fillStyle = "#454";
      ctx3.beginPath();
      ctx3.arc(150,75,35,0,Math.PI*2,true);
      ctx3.fill();

    var over = canvasOff1.getContext('2d'); 
    var under = canvasReal.getContext('2d');
    over.blendOnto(under,'multiply');

    var over2 = canvasOff3.getContext('2d'); 
    var under2 = canvasReal.getContext('2d');
    over2.blendOnto(under2,'multiply',{destX:0,destY:0});
    }

很高兴知道如何在这里实现jQuery。 感谢。

1 个答案:

答案 0 :(得分:2)

您不能将事件侦听器添加到上下文,只能添加到画布:

document.getElementById('canvasOff1').addEventLsitener(
    'click',
    function(){ goToUrl('http://www.test1.com'); }
);
document.getElementById('canvasReal').addEventLsitener(
    'click',
    function(){ goToUrl('http://www.test2.com'); }
);
document.getElementById('canvasOff3').addEventLsitener(
    'click',
    function(){ goToUrl('http://www.test3.com'); }
);

function goToUrl(url){
    window.location = url;
}

或者,使用jQuery:

$('#canvasOff1').on(
    'click',
    function(){ goToUrl('http://www.test1.com'); }
);
$('#canvasReal').on(
    'click',
    function(){ goToUrl('http://www.test2.com'); }
);
$('#canvasOff3').on(
    'click',
    function(){ goToUrl('http://www.test3.com'); }
);

function goToUrl(url){
    window.location = url;
}

(我更喜欢为window.location = X使用单独的函数,但当然,您也可以在onclick函数中使用它,如下所示:

function(){ window.location = 'http://www.test1.com'; }