在画布中制作可点击区域以更改图像 [英] make clickable region in canvas to change image

查看:17
本文介绍了在画布中制作可点击区域以更改图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮帮我:

  • 在下面的画布中创建可点击区域,我可以将 onmousedown= 事件分配给这些区域.我知道如何用不可见的 DIV 做到这一点,但我认为有一种更优雅的方式可以在我不知道的画布中做到这一点.

  • create clickable regions in the canvas below that I can assign onmousedown= events to. I know how to do this with invisible DIVs, but I think there is a more elegant way to do it in canvas that I don't know.

当我单击其中一个区域时,想要将图像名称传递给函数,以便它将正在显示的图像更改为另一个图像,然后将其更改回 onmouseup.

when I click one of the regions, want to pass an image name to a function so that it changes the image being displayed to another image, and then changes it back onmouseup.

如果您只给我展示一个区域和一个 mousedown/mouseup 示例,我可以完成剩下的...谢谢.

if you show me just one region and one mousedown/mouseup example I can do the rest...thanks.

<!DOCTYPE HTML>
<html>
<head>
</head>
<body>

        <canvas id="myCanvas" width="506" height="319" style="border:1px solid #c3c3c3;">
        Your browser does not support the canvas element.
        </canvas>

        <script type="text/javascript">
        var c=document.getElementById("myCanvas");
        var ctx=c.getContext("2d");
        var img=new Image();
        img.onload = function(){
        ctx.drawImage(img,0,0);
        };
        img.src="firstImage.gif";
        </script>

        /////////HERE NEED/////////
                    CREATE CLICKABLE REGION <region>
                    <region>
                    onmousedown=changeCanvasImage(secondImage.gif) //change image on click
                    onmouseup=changeCanvasImage(firstImage.gif)  /change it back when done
        </region>
</body>
</html>

推荐答案

canvas 元素可以触发事件,但canvas 中的图形元素不能.为此,您需要通过检测 鼠标在画布上的位置,当它被单击并将值与画布中的某些内容相关联时,或者使用许多 canvas 库可用于处理为您检测.

The canvas element can fire events but graphical elements within the canvas cannot. To do this you'll either need to implement it yourself by detecting the position of the mouse on the canvas when it is clicked and relating the value to something in your canvas, or using one of the many canvas libraries available which will handle the detection for you.

这篇关于在画布中制作可点击区域以更改图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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