【问题标题】:Drawing to selected canvas [closed]绘制到选定的画布[关闭]
【发布时间】:2014-06-30 22:45:57
【问题描述】:

我有一个以一个画布元素开头的页面。使用侧面的一些彩色按钮,我可以在此画布上添加彩色方块。

使用 jQuery,我有另一个单击事件,它将另一个画布附加到页面。 Tada,2 个画布元素。

我还创建了一个单击事件,该事件将“选定”类添加到单击的任何画布。

我的难题是,我怎样才能只在选定的画布上绘制?

【问题讨论】:

    标签: javascript jquery html canvas


    【解决方案1】:

    在 mousedown 事件处理程序中,您可以像这样获取被点击画布的 id:

    function handleMouseDown(e){
      clickedId=e.target.id;
    }
    

    然后您可以根据其 id 定位选定的画布。

    演示:http://jsfiddle.net/m1erickson/d46ZL/

    【讨论】:

      【解决方案2】:

      你也可以从类名中获取canvas元素,就像你想做的那样,使用jQuery如下:

      <!doctype html>
      <html>
          <head>
              <script src="Script/jquery-2.1.1.min.js"></script>
              <style>
                  .selected {}
              </style>
          </head>
          <body>
              <div style="margin-left: auto; margin-right: auto; width:600px;">
                  <canvas width="600" height="400" style="border:1px solid #000000;"></canvas>
              </div>
              <div style="margin-left: auto; margin-right: auto; width:600px;">
                  <canvas class="selected" width="600" height="400" style="border:1px solid #000000;"></canvas>
              </div>
          </body>
          <script>
              $(document).ready(function() {
                  var c = $(".selected").get(0);
                  var ctx = c.getContext("2d");
                  ctx.fillStyle = "#FF0000";
                  ctx.fillRect(0,0,150,75);       
              });
          </script>
      </html>
      

      【讨论】:

      • 您可能希望在选择器中包含该元素,但我尽可能简单地说明类的选择。
      猜你喜欢
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-04
      • 1970-01-01
      • 2013-11-01
      相关资源
      最近更新 更多