繁体   English   中英

画布上的矩形

[英]Rectangles on 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>

您可以侦听mousedown事件。

当用户单击“ test”(测试)时,鼠标是否位于您的直肠内,如下所示:

    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/

在此处输入图片说明

暂无
暂无

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

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