我正在 Canvas 上绘制不同颜色的方 block ,固定尺寸为 50px x 50px。
我已经成功地向这些彩色方 block 添加了 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 个单独的矩形更好的方法来实现我想要的效果?
最佳答案
是的!
您可以在矩形内部使用填充颜色,也可以在矩形周围使用描边颜色。
这里是 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>
关于html5-canvas - 在彩色方 block 上创建半透明的内部描边?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15059174/