html5-canvas - 在彩色方 block 上创建半透明的内部描边?

标签 html5-canvas

我正在 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/

相关文章:

javascript - 在纯 Javascript 中缩小图像

javascript - 为什么我不能在 Konva.Shape.fillPatternImage(imageObj) 中使用 Konva.Image()?

javascript - JavaScript Canvas 中透明框后面的模糊

javascript - setTransform 和 Scale 以使 Canvas 适合给定图像

javascript - 尝试在 React 上使用 keydown 读取和更改 useState 的值时出现未定义错误

javascript - 将 Canvas 线绘制到具有相同类名的所有 div

javascript - 如何上传/发布多个 Canvas 元素

javascript - 删除 Dygraphs 右侧的空白

javascript - wavesurfer.js play([start[, end]]) end 不起作用

javascript - 使用 html5 canvas 混合两个图像