Inner shadow/bevel with the globalCompositeOperation setting

Posted on 1st September 2017

Summary
This page shows you how you can achieve an inner shadow or bevel on your shape by using the globalCompositeOperation setting that canvas has.

As well as using the clip() function to achieve an inner shadow (for a bevelled appearance) you can also use the source-atop globalCompositeOperation. What this option does is limit the drawing to places where there's already a non-tranparent colour already on the canvas. The irregular shape below demonstrates how this method can be utilised to get an inner-shadow. The code for it is below.

[No canvas support]
<script>
    var canvas  = document.getElementById('cvs'),
        context = canvas.getContext('2d');
    
    // Draw the red fill first
    context.beginPath();
    context.fillStyle = 'red';
    context.moveTo(0,150);
    context.lineTo(60,150);
    context.quadraticCurveTo(250,0,600,150);
    context.lineTo(600,250);
    context.lineTo(50,250);
    context.closePath();
    context.fill();
    
    
    context.globalcontextmpositeOperation = 'source-atop';
    
    // Now draw the black outline a bit outside of the filled shape so the shadow falls inside
    co.beginPath();

    co.lineWidth = 6;
    co.shadowColor = 'black';
    co.shadowBlur = 25;
    co.fillStyle = 'black';

    co.moveTo(-5,147);
    co.lineTo(60,147);
    co.quadraticCurveTo(250,-3,603,147);
    co.lineTo(603,253);
    co.lineTo(47,253);
    co.closePath();
    co.stroke();
</script>

See also: