javascript - Getting single shadow for fill and stroke on HTML canvas - Stack Overflow

I have to draw a stroked fill on canvas. For this I call ctx.fill and ctx.stroke separately. Due to thi

I have to draw a stroked fill on canvas. For this I call ctx.fill and ctx.stroke separately. Due to this, the shadow of the stroke draws on top of the fill which I want to avoid.

Could somebody please tell if there is a way to avoid this?

Here is my code:

ctx1.fillStyle = "blue";
ctx1.strokeStyle = "black";
ctx1.shadowColor = "rgba(0,255,0, 1)";
ctx1.shadowOffsetX = 50; 
ctx1.shadowOffsetY = 50;
ctx1.lineWidth = "20";
ctx.beginPath();  
ctx.moveTo(300, 100);  
ctx.lineTo(400, 100);  
ctx.lineTo(400, 200);
ctx.lineTo(300, 200);
ctx.closePath();

ctx1.fill();
ctx1.stroke();

/

I have to draw a stroked fill on canvas. For this I call ctx.fill and ctx.stroke separately. Due to this, the shadow of the stroke draws on top of the fill which I want to avoid.

Could somebody please tell if there is a way to avoid this?

Here is my code:

ctx1.fillStyle = "blue";
ctx1.strokeStyle = "black";
ctx1.shadowColor = "rgba(0,255,0, 1)";
ctx1.shadowOffsetX = 50; 
ctx1.shadowOffsetY = 50;
ctx1.lineWidth = "20";
ctx.beginPath();  
ctx.moveTo(300, 100);  
ctx.lineTo(400, 100);  
ctx.lineTo(400, 200);
ctx.lineTo(300, 200);
ctx.closePath();

ctx1.fill();
ctx1.stroke();

http://jsfiddle/abWYZ/3/

Share Improve this question edited Feb 6, 2021 at 1:03 ggorlen 58k8 gold badges114 silver badges157 bronze badges asked Nov 20, 2012 at 9:27 RahulRahul 8801 gold badge13 silver badges28 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

Every time you perform a draw action on the context the shadow is also drawn. The way canvas works is every thing that's drawn is placed on top of what was previously there. So whats happening is the fill is performed, making a shadow of it, and then the stroke is drawn, which makes a shadow on top of all previous drawn objects.

Here is one possible solution.

Live Demo

 // Grab the Canvas and Drawing Context
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');

ctx.save();
ctx.fillStyle = "blue";
ctx.strokeStyle  = "black";

ctx.lineWidth="20";
ctx.beginPath();  
ctx.moveTo(300, 100);  
ctx.lineTo(400, 100);  
ctx.lineTo(400, 200);
ctx.lineTo(300, 200);
ctx.closePath();

ctx.shadowColor = "rgba(0,255,0, 1)";
ctx.shadowOffsetX = 50; 
ctx.shadowOffsetY = 50;

ctx.stroke();
ctx.fill();
// clear the shadow
ctx.shadowColor = 0;
ctx.shadowOffsetX = 0; 
ctx.shadowOffsetY = 0;

// restroke w/o the shadow
ctx.stroke();

If you use an approach like this I suggest making a function called toggleShadow or something along those lines allowing you to control when the shadows are drawn.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744736837a4590799.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信