2

50pxx50pxの固定サイズでキャンバスにさまざまな色の正方形を描いています。

これらの色付きの正方形に5pxの透明な内側のストロークを追加することに成功しましたが、私が行っている方法では大規模なやり過ぎのようです。

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

私が求めているものを達成するために、3つの別々の長方形を描くよりも良い方法はありますか?

4

1 に答える 1

5

はい!

長方形の内側の塗りつぶしの色と、長方形の周りの線の色の両方を使用できます。

これがフィドルのコードです: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>
于 2013-02-25T03:04:15.990 に答える