简体   繁体   English

画布绘制对象的鼠标事件

[英]Mouse events for canvas draw objects

I want to create canvas-based site menu using this plugin, to create 'multiply' effect. 我想使用这个插件创建基于画布的网站菜单,以创建“乘法”效果。 However this, and also globalCompositeOperation , are working on ctx objects in the same canvas. 然而,这个以及globalCompositeOperation正在同一个画布中处理ctx对象。 (in context-blender it uses an off-screen canvas and uses its draw info, globalcompoperation blends the same ctx). (在上下文混合器中,它使用离屏画布并使用其绘制信息,globalcompoperation混合相同的ctx)。 I want to create mouse events (hover and click) for each ctx object, so each ctx will lead to a different url. 我想为每个ctx对象创建鼠标事件(悬停和单击),因此每个ctx将导致不同的URL。

Here is my test: 这是我的测试:

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

Would be nice to know though how Can I implement jQuery here. 很高兴知道如何在这里实现jQuery。 Thanks. 谢谢。

You can't add event listeners to a context, only to the canvas: 您不能将事件侦听器添加到上下文,只能添加到画布:

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

Or, with jQuery: 或者,使用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;
}

(I prefer using a separate function for window.location = X , but of course, you couls also use it in the onclick function, like this: (我更喜欢为window.location = X使用单独的函数,但当然,你也可以在onclick函数中使用它,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM