javascript 将点击事件添加到画布或制作区域地图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19133825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:30:11  来源:igfitidea点击:

Add click event to canvas or make area map

javascripthtmlcanvas

提问by mgh

I write this html code :

我写了这个 html 代码:

<div id="container">
        <canvas id="imageView" width="1181" height="1181">
            <p>Unfortunately, your browser is currently unsupported by our web 
                application.</p>
        </canvas>
        <script type="text/javascript">
            window.onload = function() {
                var c = document.getElementById('imageView');
                var cxt = c.getContext('2d');
                var img = new Image();
                img.src = "map.jpg";
                cxt.drawImage(img, 0, 0);
            };
        </script>
</div>

And write this javascript :

并写下这个 javascript :

this.mousemove = function(ev) {
                        if (!tool.started) {
                            return;
                        }

                        var x = Math.min(ev._x, tool.x0),
                                y = Math.min(ev._y, tool.y0),
                                w = Math.abs(ev._x - tool.x0),
                                h = Math.abs(ev._y - tool.y0);
                        context.clearRect(0, 0, canvas.width, canvas.height);
                        if (!w || !h) {
                            return;
                        }
                        context.clearRect(x, y, w, h);
                        context.strokeRect(x, y, w, h);

this code is make a rectangle . I want change this rectangle to a area map , that when I click on the area do something , (for example open google.com) .

这段代码是制作一个矩形。我想将此矩形更改为区域地图,当我单击该区域时执行某些操作(例如打开 google.com)。

回答by

If I understand you correctly you want to invoke a function when you hit a pixel on the actual map - not just in the map area.

如果我理解正确,您想在实际地图上点击像素时调用一个函数 - 而不仅仅是在地图区域。

Method 1

方法一

You can check a map click in more than one way. You can simply check for the pixel value at the click point to check if it is inside the area you want it to be by comparing the map color value.

您可以通过多种方式检查地图点击。您可以简单地检查点击点的像素值,通过比较地图颜色值来检查它是否在您想要的区域内。

I provided an example below for this method.

我在下面为此方法提供了一个示例。

Method 2

方法二

You can pre-define a polygon which traces the outline of the map area you want to check.

您可以预先定义一个多边形来追踪要检查的地图区域的轮廓。

Then build a path (ctx.beginPath();and ctx.lineTo(..);etc.) to allow the use of the method:

然后生成的路径(ctx.beginPath();ctx.lineTo(..);等),以允许使用该方法:

if (ctx.isPointInPath(x, y)) { ... };

This is a good method if you have small regions to check.

如果您要检查小区域,这是一个很好的方法。

Method 3

方法三

Store a separate image of the map containing only a matte(sort of an alpha map), That is usually black (or transparent) for non-clickable areas, white for clickable areas.

存储仅包含遮罩(某种 alpha 贴图)的单独地图图像,对于不可点击区域通常为黑色(或透明),对于可点击区域为白色。

This is useful if your map is complex color-wise and a simple pixel value check is not trivial.

如果您的地图在颜色方面很复杂并且简单的像素值检查不是微不足道的,这将非常有用。

And speaking of which: you can even provide different solid color values for different areas so that you can define red color = USA, blue = Argentina, etc. As these are not visible to the user the only thing that matters is that the color value can be recognized (for this reason don't save images for this use with an ICC color profile).

说到这一点:您甚至可以为不同的区域提供不同的纯色值,以便您可以定义红色 = 美国、蓝色 = 阿根廷等。由于这些对用户不可见,唯一重要的是颜色值可以识别(因此,不要使用 ICC 颜色配置文件保存用于此用途的图像)。

Then project the mouse position from the click onto the matte image (which is basically an off-screen canvas where the matte image is drawn into) and check for the color (white or other color).

然后将鼠标位置从点击投影到哑光图像(它基本上是一个绘制哑光图像的屏幕外画布)并检查颜色(白色或其他颜色)。

Example for method 1

方法 1 的示例

This is a simple example, but in any case there are a couple of things you need to know in advance:

这是一个简单的示例,但无论如何,您需要提前了解以下几点:

  1. That the image is loaded from same server as the page or from a domain that allow cross-origin use. Or else you cannot grab a pixel from the map due to security reasons.
  2. You need to know what color or alpha value to check for. If the map is solid and everything is transparent you just need to check for alpha value above zero (as in this example), and if not just check the RGB value of the region you want to trigger an action with.
  1. 图像是从与页面相同的服务器或从允许跨域使用的域加载的。否则,出于安全原因,您无法从地图中获取像素。
  2. 您需要知道要检查的颜色或 alpha 值。如果地图是实心的并且一切都是透明的,您只需要检查 alpha 值是否高于零(如本例所示),如果不是,则只需检查要触发操作的区域的 RGB 值。

ONLINE DEMO HERE

在线演示在这里

HTML:

HTML:

<canvas width=725 height=420 id="demo"></canvas>

JavaScript:

JavaScript:

var ctx = demo.getContext('2d'),
    img = new Image();

/// we need to wait for the image to actually load:
img.onload = function() {

    /// image is loaded and we can raw it onto canvas
    ctx.drawImage(this, 0, 0);

    /// enable mouse click
    demo.onclick = function(e) {

        /// adjust mouse position to be relative to canvas
        var rect = demo.getBoundingClientRect(),
            x = e.clientX - rect.left,
            y = e.clientY - rect.top;

        /// grab a pixel
        var data = ctx.getImageData(x, y, 1, 1).data;

        /// check it's alpha value to see if we're in a map point
        /// this of course assumes the map has transparent areas.
        /// if not just check for the color values instead.
        if (data[3] > 0) alert('We hit map');
    }   
}

/// we need crossOrigin allowed image or we can't grab pixel later
img.crossOrigin = 'anonymous';
img.src = 'http://i.imgur.com/x8Ap3ij.png';

Just replace the alert with:

只需将警报替换为:

window.open('http://google.com/');

if you want it to open a new window/tab.

如果您希望它打开一个新窗口/选项卡。

回答by markE

You can turn canvas into an anchor link by using addEventListenerto listen for clicks on the canvas.

您可以通过使用addEventListener侦听画布上的点击将画布变成锚链接。

Then you can use window.opento open google in a new browser tab.

然后您可以使用window.open在新的浏览器选项卡中打开谷歌。

Also, you need to use image.onloadto give your image time to load before using drawing it.

此外,image.onload在使用绘图之前,您需要使用给图像加载时间。

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");


var img=new Image();
img.onload=function(){
    ctx.drawImage(img,0,0);
    canvas.addEventListener("click",function(){
        window.open("http://google.com");
    });
}
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/google.jpg";