Created
February 13, 2014 20:45
-
-
Save alexeypegov/8983455 to your computer and use it in GitHub Desktop.
HTML5 Canvas Shadow (Opposite Winding solution)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* <canvas id="c" width="200" height="200"></canvas> */ | |
function retina(canvas, context) { | |
var ratio = window.devicePixelRatio || 1, | |
width = canvas.width, | |
height = canvas.height; | |
if (ratio > 1) { | |
canvas.width = width * ratio; | |
canvas.height = height * ratio; | |
canvas.style.width = width + "px"; | |
canvas.style.height = height + "px"; | |
context.scale(ratio, ratio); | |
} | |
} | |
function roundRect(context, x, y, w, h, radius) | |
{ | |
var r = x + w; | |
var b = y + h; | |
context.moveTo(x+radius, y); | |
context.lineTo(r-radius, y); | |
context.quadraticCurveTo(r, y, r, y+radius); | |
context.lineTo(r, y+h-radius); | |
context.quadraticCurveTo(r, b, r-radius, b); | |
context.lineTo(x+radius, b); | |
context.quadraticCurveTo(x, b, x, b-radius); | |
context.lineTo(x, y+radius); | |
context.quadraticCurveTo(x, y, x+radius, y); | |
} | |
var canvas = document.getElementById("c"); | |
var ctx = canvas.getContext("2d"); | |
retina(canvas, ctx); | |
ctx.beginPath(); | |
ctx.rect(0, 0, 200, 200); | |
ctx.strokeStyle = "#ccc"; | |
ctx.stroke(); | |
ctx.closePath(); | |
ctx.fillStyle = "#bbb"; | |
ctx.translate(50, 50); | |
ctx.beginPath(); | |
roundRect(ctx, 0, 0, 100, 100, 6); | |
ctx.fill(); | |
ctx.clip(); | |
ctx.shadowColor = "#444"; | |
ctx.shadowOffsetX = 2; | |
ctx.shadowOffsetY = 2; | |
ctx.shadowBlur = 3; | |
ctx.beginPath(); | |
// opposite winding: | |
// anti-clockwise | |
ctx.moveTo(-25, -25); | |
ctx.lineTo(-25, 125); | |
ctx.lineTo(125, 125); | |
ctx.lineTo(125, -25); | |
ctx.lineTo(-25, -25); | |
// clockwise | |
roundRect(ctx, 0, 0, 100, 100, 6); | |
ctx.closePath(); | |
ctx.fill(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment