ShaShads
ShaShads

Reputation: 572

Creating an inner stroke of semi transparency on coloured squares?

I am drawing different colored squares on canvas with a fixed size of 50px x 50px.

I have successfully added a transparent inner stroke of 5px to these colored squares but it seems like massive overkill the way I am doing it.

ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, engine.cellSize, engine.cellSize);
ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
ctx.fillRect(this.x, this.y, engine.cellSize, engine.cellSize);
ctx.fillStyle = this.color;
ctx.fillRect(this.x + 5, this.y + 5, engine.cellSize - 10, engine.cellSize - 10);

Is there a better way than drawing 3 separate rectangles to achieve what I am after?

Upvotes: 2

Views: 2664

Answers (1)

markE
markE

Reputation: 105015

Yes!

You can use both a fill color inside your rectangle and a stroke color around your rectangle.

Here is code an a Fiddle: http://jsfiddle.net/m1erickson/myGky/

<!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(){

      var canvas=document.getElementById("canvas");
      var ctx=canvas.getContext("2d");

      ctx.beginPath();
      ctx.fillStyle = "red";
      ctx.fillRect(100,100,50,50);
      ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
      ctx.fillRect(100,100,50,50);
      ctx.fillStyle = this.color;
      ctx.fillRect(105, 105, 40, 40);
      ctx.fill();

      ctx.beginPath();
      ctx.rect(160,102.5,45,45);
      ctx.fillStyle = 'rgb(163,0,0)';
      ctx.fill();
      ctx.lineWidth = 5;
      ctx.strokeStyle = 'rgb(204,0,0)';
      ctx.stroke();

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

</head>

<body>
   <canvas id="canvas" width=600 height=400></canvas>
</body>
</html>

Upvotes: 5

Related Questions