javascripthtml5-canvas

Inset Box Shadow Gets Hidden On Filling Rect


I am having a canvas and there is an inset box shadow. However, the box shadow is well shown but on calling fillRect at every time using requestAnimationFrame, it gets hidden.

I tried to again set the box shadow after fillrect but still got not good results

Here is a codepen link: https://codepen.io/asiancat54x/pen/ExXNLzj

Here is the snippet

const canvas = document.querySelector("canvas")
const c = canvas.getContext("2d")

canvas.width = innerWidth

canvas.height = innerHeight

function a(){
  c.fillRect(0 , 0 , canvas.width , canvas.height)
  
  canvas.boxShadow = "box-shadow: inset 0 0 60px 5px red, 3px 3px 5px 0 red;"

  requestAnimationFrame(a)
}

a()
.header {
  background-color: #2e3440;
  box-shadow: inset 0 0 60px 5px red,
    3px 3px 5px 0 red;
  height: 500px;
  width: 500px;
}
This is with a div element

<div class="header"></div>

Cannot create such box shadow on canvas

<br>

<canvas class="header"></canvas>


Solution

  • I am not exactly sure why Inset Box Shadow on canvas doesn't work.

    But I quickly created a hack. See if this works for you. It basically draws a DIV as well as canvas with DIV over the canvas having transparent background but a box shadow. https://codepen.io/hariom_balhara/pen/RwgoJRQ

    const canvas = document.querySelector("canvas")
    const c = canvas.getContext("2d")
    c.fillStyle='green'
    canvas.width = innerWidth
    
    canvas.height = innerHeight
    
    function a(){
      c.fillRect(0 , 0 , canvas.width , canvas.height)
      
      canvas.boxShadow = "box-shadow: inset 0 0 60px 5px red, 3px 3px 5px 0 red;"
    
      requestAnimationFrame(a)
    }
    
    a()
    .header {
      position:absolute;
      background-color: #2e3440;
      box-shadow: inset 0 0 60px 5px red,
        3px 3px 5px 0 red;
      height: 500px;
      width: 500px;
    }
    This is with a div element
    
    
    
    Cannot create such box shadow on canvas
    
    <br>
    <div style="position:relative">
      <div class="header" style="z-index:1;background:transparent"></div>
      <canvas class="header">  </canvas>
    </div>