HTML5 Canvas中的图片点击事件 [英] Image Click Event in HTML5 Canvas

查看:3765
本文介绍了HTML5 Canvas中的图片点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML5画布,我已经添加了一个图像,我想调用图像的点击事件,但事件不会触发。我写了一个HTML代码和一些代码jqmobile

I have a HTML5 canvas and I have added an image in it and I want to call click event of image but event doesn't fire. I am writing a html code and some code of jqmobile

<html>
<head>
    <script src="jquery-1.10.2.min.js"></script>
    <script src="jquery.mobile-1.2.1.js"></script>
    <script src="jquery.mobile-1.2.1.min.js"></script>
</head>
<body>
    <canvas id="canvas1" style="position: absolute; left: 0px; top: 0px;" width="1280" height="960">This text is displayed if your browser does not shown.
    </canvas>
    <script>
        $(function () {

            var ctx = document.getElementById("canvas1").getContext("2d");
            var imgBasket = new Image();
            imgBasket.id = "imgBasket";
            imgBasket.src = "Basket.png";
            ctx.drawImage(imgBasket, 580, 260, 200, 200);


            //this jquery mobile event not working in canvas
            $("document").on("vclick", "#imgBasket", function () {
                alert("Hello");
            });
        });
    </script>
</body>
</html>


推荐答案

现在我明白你想达到什么想要将图像放在画布上,然后使用jquery查看您点击图片的时间。好吧,可悲的是,它不工作像这样。画布中的图像不再是dom元素,只有画布本身是一个。这意味着你可以调用:

Now I understand what you are trying to achieve, you want to put an image in a canvas and then use jquery to see when you clicked on the image. Well, sadly, it doesn't work like this. Images in the canvas are no longer dom elements, only the canvas itself is one. This means you can call:

$('#canvas').on('click', function() {});

但您无法呼叫

$("document").on("click", "#canvasImage", function () {});

因为#canvasImage不存在,即使原始图像是dom节点。
如果真的没有其他方法去使用你的项目,fabricjs可能会有帮助:

Because the #canvasImage isn't there, even if the original image was a dom node. If there's really no other way of going with your project, fabricjs might help:

http://fabricjs.com/

这篇关于HTML5 Canvas中的图片点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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