Skip to content

Instantly share code, notes, and snippets.

@MalucoMarinero
Created December 26, 2014 00:29
Show Gist options
  • Save MalucoMarinero/6f5902cc070a1e5b5548 to your computer and use it in GitHub Desktop.
Save MalucoMarinero/6f5902cc070a1e5b5548 to your computer and use it in GitHub Desktop.
PostCSS - IE8 RGBA Background using Data URIs
postcss = require "postcss"
fs = require 'fs'
{Png} = require "png"
{Buffer} = require "buffer"
makePng = (r, g, b, a) ->
WIDTH = 64
HEIGHT = 64
alpha255 = 0xff * a
rgba = new Buffer(WIDTH*HEIGHT*4)
for x in [0..HEIGHT]
for y in [0..WIDTH]
basePoint = x * WIDTH * 4 + y * 4
rgba[basePoint + 0] = parseInt(r)
rgba[basePoint + 1] = parseInt(g)
rgba[basePoint + 2] = parseInt(b)
rgba[basePoint + 3] = 255 - parseInt(alpha255) # alpha is inversed in png
png = new Png(rgba, WIDTH, HEIGHT, 'rgba')
return png.encodeSync().toString("base64")
IE8BackgroundPolyfill = (css, opts) ->
css.eachRule (rule) ->
rule.eachDecl (decl) ->
if decl.prop in ["background", "background-color"]
if decl.value.slice(0,4) == "rgba"
values = decl.value.replace("rgba(", "").replace(")", "")
values = values.split(",").map((v) -> parseFloat(v.trim()))
[r,g,b,a] = values
encodedPNG = makePng(r,g,b,a)
rule.insertAfter(decl, postcss.decl({
prop: "background",
value: "url(data:image/png;base64,#{ encodedPNG}) repeat"
}))
IE8BackgroundPolyfill.makePng = makePng
module.exports = IE8BackgroundPolyfill
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment