javascript canvas检测点击形状 [英] javascript canvas detect click on shape

查看:253
本文介绍了javascript canvas检测点击形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中的点击功能有问题。这是我的代码:

I have a problem with the click function in javascript. This is my code:

var canvas = document.getElementsByTagName("canvas")[0];
var ctx = canvas.getContext('2d');

BigCircle = function(x, y, color, circleSize) {
    ctx.shadowBlur = 10;
    ctx.shadowColor = color;
    ctx.beginPath();
    ctx.arc(x, y, circleSize, 0, Math.PI * 2, true);
    ctx.fill();
    ctx.closePath();
};

var bigGreen = new BigCircle(1580, 800, '#5eb62b', 180);

function init() {
    $("#bigGreen").click(function(e){
    alert("test");              
    });
}
$(document).ready(function() {
    init();
});

但是点击事件不工作!有人知道为什么吗?非常感谢你!

But the click event is not working! Does anybody know why? Thank you so much in advance!

推荐答案

没有看到你的html这个问题有点不清楚,你似乎想在画布上绘制一些东西,并使用jquery为圆圈添加点击事件,这是不可能的。

without seeing your html this question is a little bit unclear, it seems you would like to draw something on a canvas and use jquery to add click events for the circle, this isn't possible.

您可以使用jquery在画布上获取点击事件从光标位置,你可以计算是否用户点击了圆圈,但是jquery不会帮助你在这里你自己做数学。

you can use jquery to get the click event ON the canvas and from the cursor position you can calculate if the user clicked the circle or not, but jquery won't help you here you have to do the math yourself.

jquery只有为dom元素工作。

jquery does only work for dom elements.

BigCircle = function(ctx,x, y, color, circleSize) {
    ctx.beginPath();
    ctx.arc(x, y, circleSize, 0, Math.PI * 2, true);
    ctx.fillStyle=color
    ctx.fill();
    ctx.closePath();
    this.clicked=function(){
      ctx.fillStyle='#ff0000'
      ctx.fill();
    }
};

function init() {
  var canvas = document.getElementsByTagName("canvas")[0];
  var ctx = canvas.getContext('2d');
  var bigGreen = new BigCircle(ctx,50, 50, '#5eb62b', 50);
  $('#canvas').click(function(e){
    var x = e.clientX
      , y = e.clientY          
    if(Math.pow(x-50,2)+Math.pow(y-50,2) < Math.pow(50,2))   
      bigGreen.clicked()
  })    
}


$(document).ready(function() {
    init();   
});

jsfiddle $ b http://jsfiddle.net/yXVrk/1/

jsfiddle is here http://jsfiddle.net/yXVrk/1/

这篇关于javascript canvas检测点击形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆