简体   繁体   中英

Getting single shadow for fill and stroke on HTML canvas

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.net/abWYZ/3/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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