繁体   English   中英

Canvas 用边框画线

[英]Canvas draw line with border

我需要画一条线并给它一个边框。

我试着画两条线,一条 5px 和 3px 以上

但这看起来并不像真正的边界

 const ctx = canvas.getContext('2d'); const path = new Path2D(); ctx.strokeStyle = "black"; ctx.lineWidth = 5; path.moveTo(40, 40); path.lineTo(50, 35); path.lineTo(60, 40); ctx.stroke(path); ctx.strokeStyle = "red"; ctx.lineWidth = 3; path.moveTo(40, 40); path.lineTo(50, 35); path.lineTo(60, 40); ctx.stroke(path);
 <canvas id=canvas width=100 height=100></canvas>

有没有更好的方法来绘制一条线的边框?

尝试在外线上设置“endCap”:

const ctx = canvas.getContext('2d');
const path = new Path2D();

ctx.strokeStyle = "black";
ctx.lineWidth = 5;
ctx.lineCap = "butt"; // butt  round  square <-- other options

path.moveTo(40, 40);
path.lineTo(50, 35);
path.lineTo(60, 40);

ctx.stroke(path);

ctx.strokeStyle = "red";
ctx.lineWidth = 3;

path.moveTo(40, 40);
path.lineTo(50, 35);
path.lineTo(60, 40);

ctx.stroke(path);

请参阅: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineCap

您可以尝试使用阴影:

 const ctx = canvas.getContext('2d'); function drawPath(path) { ctx.lineWidth = 3; ctx.strokeStyle = "red"; ctx.shadowColor = 'black'; for (i = 0; i <= 360; i += 10) { a = i * Math.PI / 180 ctx.beginPath(); ctx.shadowOffsetX = 4 * Math.sin(a) ctx.shadowOffsetY = 4 * Math.cos(a) ctx.stroke(path); } } const path = new Path2D(); path.moveTo(20, 40); path.lineTo(50, 35); path.lineTo(80, 40); path.lineTo(80, 80); path.lineTo(160, 80); drawPath(path);
 <canvas id=canvas width=200 height=100></canvas>

这个想法是在你的路径 object 周围绘制一个稍微不同的偏移量......并且相同的逻辑可以用于图像:

https://raw.githack.com/heldersepu/hs-scripts/master/HTML/canvasOutline.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM