最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论