2013-02-25 66 views
2

我在画布上绘制了不同的彩色正方形,大小为50px x 50px。在彩色方块上创建半透明的内部中风?

我已经成功地为这些彩色正方形添加了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个单独的矩形来实现我所追求的更好的方法?

回答

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>