简体   繁体   English

如何使html中的canvas元素可点击?

[英]How to make canvas element in html clickable?

I am designing a web page which has a lot of mathematical figures .eg rhombus ,square ,rectangle,triangle etc.... 我正在设计一个有很多数学数字的网页。例如菱形,正方形,矩形,三角形......

what I am trying to achieve is ,when I click on any of the figures ,it should show up a msg /info kind of thing. 我想要实现的是,当我点击任何一个数字时,它应该显示一个msg / info类的东西。

I have only one canvas id ,and lot of figures in it ,how i make them clickable so that I can display the required info from each figure 我只有一个画布ID,其中有很多数字,我如何使它们可点击以便我可以显示每个图形所需的信息

Here's how to use native html canvas to let users get a message about the shape they clicked: 以下是如何使用原生html画布让用户收到有关他们点击的形状的消息:

  • for each shape, put their corner points in a javascript object 对于每个形状,将它们的角点放在javascript对象中
  • put all those shape-objects in an array 将所有这些形状对象放在一个数组中
  • listen for mousedown events 听mousedown事件
  • in mousedown check if the mouse is inside each shape using context.isPointInPath 在mousedown中使用context.isPointInPath检查鼠标是否在每个形状内
  • if the mouse is inside an object, display your message about that shape 如果鼠标位于对象内,则显示有关该形状的消息

A Demo: http://jsfiddle.net/m1erickson/wPMk5/ 演示: http//jsfiddle.net/m1erickson/wPMk5/

Example code: 示例代码:

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    #canvas{border:1px solid red;}
</style>

<script>
$(function(){

    // canvas variables
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var $canvas=$("#canvas");
    var canvasOffset=$canvas.offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;
    var scrollX=$canvas.scrollLeft();
    var scrollY=$canvas.scrollTop();

    // set styles
    ctx.fillStyle="skyblue";
    ctx.strokeStyle="lightgray";
    ctx.lineWidth=2;

    // create a triangle and parallelogram object

    var triangle={
        points:[{x:25,y:100},{x:50,y:50},{x:75,y:100}],
        message:"I am a triangle"
    }

    var parallelogram={
        points:[{x:150,y:50},{x:250,y:50},{x:200,y:100},{x:100,y:100}],
        message:"I am a parallelogram"
    }

    // save the triangle and parallelogram in a shapes[] array

    var shapes=[];
    shapes.push(triangle);
    shapes.push(parallelogram);

    // function to draw (but not fill/stroke) a shape
    // (needed because isPointInPath only tests the last defined path)

    function define(shape){
        var points=shape.points;
        ctx.beginPath();
        ctx.moveTo(points[0].x,points[0].y);
        for(var i=1;i<points.length;i++){
            ctx.lineTo(points[i].x,points[i].y);
        }
    }

    // function to display a shape on the canvas (define + fill + stroke)

    function draw(shape){
        define(shape);
        ctx.fill();
        ctx.stroke();
    }

    // display the triangle and parallelogram
    draw(triangle);
    draw(parallelogram);


    // called when user clicks the mouse

    function handleMouseDown(e){
      e.preventDefault();

      // get the mouse position
      var mouseX=parseInt(e.clientX-offsetX);
      var mouseY=parseInt(e.clientY-offsetY);

      // iterate each shape in the shapes array
      for(var i=0;i<shapes.length;i++){
          var shape=shapes[i];
          // define the current shape
          define(shape);
          // test if the mouse is in the current shape
          if(ctx.isPointInPath(mouseX,mouseY)){
              // if inside, display the shape's message
              alert(shape.message);
          }
      }

    }

    // listen for mousedown events
    $("#canvas").mousedown(function(e){handleMouseDown(e);});

}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

If you can use SVG instead you can achive this goal very easily. 如果您可以使用SVG,则可以非常轻松地实现此目标。 Using http://svg-edit.googlecode.com/svn/branches/2.5.1/editor/svg-editor.html you can draw relevant shapes and you can get the svg code. 使用http://svg-edit.googlecode.com/svn/branches/2.5.1/editor/svg-editor.html可以绘制相关的形状,你可以获得svg代码。 Add onclick() events to it . 添加onclick()事件。

By this online tool you can create shapes 通过此在线工具,您可以创建形状 在此输入图像描述

Click SVG to get the code 单击SVG以获取代码

在此输入图像描述

Code

<svg width="640" height="480" xmlns="http://www.w3.org/2000/svg">
 <!-- Created with SVG-edit - http://svg-edit.googlecode.com/ -->
 <g>
  <title>Layer 1</title>
  <rect id="svg_1" height="74" width="150" y="95" x="58" stroke-width="5" stroke="#000000" fill="#FF0000"/>
  <ellipse ry="35" rx="42" id="svg_2" cy="216" cx="158" stroke-width="5" stroke="#000000" fill="#FF0000"/>
  <ellipse ry="36" rx="80" id="svg_3" cy="123" cx="342" stroke-width="5" stroke="#000000" fill="#0000ff"/>
  <path id="svg_4" d="m265,257l63,-59l82,47l-22,71l-84,5l-39,-64z" stroke-width="5" stroke="#000000" fill="#0000ff"/>
 </g>
</svg>

You can add onclick events to this.And also following shows adding jquery title mouse over also. 您可以向此添加onclick事件。此外,还显示了添加jquery标题鼠标。

 <rect id="svg_29" class="popup_tool" title="Message you want to popup when mouse over" height="17" width="20" y="224" x="452" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke-width="3" stroke="#000000" fill="#ff0000"/> 

Hope you got the answer 希望你能得到答案

只需将canvas id包装在div元素中,之后你可以使用js / jquery隐藏或显示div,你可以显示你的消息

要使用canvas元素轻松实现任务,您需要一个像fabricjs这样的框架

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

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