Canvas inner stroke

旧城冷巷雨未停 提交于 2020-04-29 09:38:00

问题


I studied strokeStyle a bit but I cant find how to control the position of the stroke from inner/center/outer. It seems all stroke is outside the rectangle I draw. Is there anyway make the stroke be inner? (or even centered on the rectangle bounds)?

Thanks


回答1:


The default stroke do use centered stroke but there is unfortunately no parameter to control the alignment of the stroke so you would either have to calculate an offset value for the rectangle's position and size, or combine two rectangles and use for example the fill-rule evenodd:

var ctx = c.getContext("2d");

// default centered
ctx.lineWidth = 10;
ctx.strokeRect(10, 10, 100, 100);

ctx.lineWidth = 1;
ctx.strokeStyle = "red";
ctx.strokeRect(10, 10, 100, 100);         // show main path

// inner
ctx.rect(150, 10, 100, 100);
ctx.rect(150+10, 10+10, 100-20, 100-20);  // offset position and size
ctx.fill("evenodd");                      // !important
ctx.strokeRect(150, 10, 100, 100);
<canvas id=c></canvas>



回答2:


Hope this helps!

Instead of doing:

ctx.fill();
ctx.stroke();

DO:

ctx.save();
ctx.clip();
ctx.lineWidth *= 2;
ctx.fill();
ctx.stroke();
ctx.restore();

Edit

For me I believe this works because the clip method removes any fill and stroke around the already present fill area, meaning the only place the stroke can go is on the inside because else it would be clipped off.




回答3:


This answer "Draw outer and inner border around any canvas shape" shows how to use masking and compositing to precisely control the offset, both inwards and outwards of a stroke without the need to manipulate paths. It can be used for any canvas path no matter how complex.



来源:https://stackoverflow.com/questions/36615592/canvas-inner-stroke

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!