画布上的矩形

时间:2014-02-04 21:07:49

标签: javascript html canvas

我希望能够根据所做的选择更改对象的颜色。 我的画布上有3个矩形(假设矩形是a,b& c)如何更改被点击的矩形的颜色?

例如:如果单击“b”,然后选择橙色,则只有B应将颜色更改为橙​​色。

<a class="button" style="background-color: #000;" onClick="clur1()"></a>
<a class="button" style="background-color: #FF6600;" onClick="clur2()"></a>
<a class="button" style="background-color: #00C4FF;" onClick="clur3()"></a>

<p id="clurN">Empty</p>

<canvas id="myCanvas" width="200" height="100" style="background-color: #C4C4C4;">

<script>
function Shape(x, y, w, h, fill) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.fill = fill;
}

var elem = document.getElementById('myCanvas');
if (elem.getContext) {
    var myRect = [];
    myRect.push(new Shape(10, 0, 25, 25, "#333"));
    myRect.push(new Shape(0, 40, 39, 25, "#333"));
    myRect.push(new Shape(0, 80, 100, 25, "#333"));

    context = elem.getContext('2d');
    for (var i in myRect) {
        oRec = myRect[i];
        context.fillStyle = oRec.fill;
        context.fillRect(oRec.x, oRec.y, oRec.w, oRec.h);
    }
}
function clur1() {
    //Store the element in the variable:
    var paragraph = document.getElementById("clurN");

    //change the element's inner HTML:
    paragraph.innerHTML = "Done!!";

    var c=document.getElementById("c1Canvas");
    var ctx=c.getContext("2d");
    ctx.fillStyle="#FF0000";
    ctx.fillRect(0,0,150,75);
}
</script>
</canvas>

1 个答案:

答案 0 :(得分:0)

你可以听mousedown事件。

当用户点击测试时,如果鼠标位于您的其中一个内部,请执行以下操作:

    function handleMouseDown(e){
      e.preventDefault();
      var x=parseInt(e.clientX-offsetX);
      var y=parseInt(e.clientY-offsetY);

      // iterate every rect and recolor any that are under x/y
      for(var i=0;i<myRect.length;i++){
          var oRec=myRect[i];
          if(x>=oRec.x && x<=oRec.x+oRec.w && y>=oRec.y && y<=oRec.y+oRec.h){
              oRec.fill=currentColor;
              // drawRect will redraw the specified rectangle
              drawRect(oRec);
          }
      }
    }

演示:http://jsfiddle.net/m1erickson/48BMC/

enter image description here

相关问题