Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw only shadows on html5-canvas

I'm trying to figure out how I can draw something on canvas and show only it's shadow, for example:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.shadowBlur=100;
ctx.shadowOffsetX = 150;
ctx.shadowColor="red";
ctx.fillStyle="rgba(0,0,0,0.7)";
ctx.fillRect(20,20,100,80);

Here I draw a black rectangle and add a red shadow with an offset, I'd like to see only the shadow without the rectangle.

As you can see on the example, I tried using rgba color but when I set opacity it affects the shadow as well.

here is a fiddle for this code: http://jsfiddle.net/YYvFw/

like image 871
Gilad_Gr Avatar asked Jun 12 '13 09:06

Gilad_Gr


People also ask

How do I add a shadow to text in canvas?

To add shadow to text, use the shadowOffsetX and shadowOffsetY attributes. shadowOffsetX = number of pixels offset in the x direction; shadowOffsetY = number of pixels offset in the y direction; A blur effect added to the shadows will make the text beveled.

Does HTML5 support canvas element?

The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images.


1 Answers

well the first thing that comes to mind is moving the rectangle out of the canvas and offsetting the shadow as far as you need it.

    var canvas = document.getElementById('myCanvas'),
    context = canvas.getContext('2d'),
    width = 100,
    height = 80,
    posX = 100,
    posY = 80;

    context.rect(-width, -height, width, height);
    context.shadowColor = 'red';
    context.shadowBlur = 40;
    context.shadowOffsetX = width+posX;
    context.shadowOffsetY = height+posY;
    context.fill();

that draws you the shadow at x:100 y:80

http://jsfiddle.net/S7WRx/2/

like image 163
yardarrat Avatar answered Sep 28 '22 02:09

yardarrat