简体   繁体   中英

Rectangles on canvas

I want to be able to change the color of an object based on the selection made. There are 3 rectangles on my Canvas (assume the rectangles are a,b & c) how can I change the color of the rectangle which was clicked?

Eg: if "b" was clicked, and then orange was selected, only B should change the color to orange.

<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>

You can listen for mousedown events.

When the user clicks test if the mouse was inside one of your rects like this:

    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);
          }
      }
    }

Demo: http://jsfiddle.net/m1erickson/48BMC/

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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