Skip to content

Instantly share code, notes, and snippets.

@tikhiy
Created December 29, 2021 17:20
Show Gist options
  • Save tikhiy/c2a87797c163f0e1d825fd07ead0b446 to your computer and use it in GitHub Desktop.
Save tikhiy/c2a87797c163f0e1d825fd07ead0b446 to your computer and use it in GitHub Desktop.
Save Brandmark As PNG From app.brandmark.io
// $0 = .logo-inner > svg
const FILENAME = "brandmark.png"
const HEIGHT = 3840
const SCALE = 1
const WIDTH = 3840
const OCTET_STREAM = "image/octet-stream"
const PNG = "image/png"
const SVG = "image/svg+xml"
const canvas = document.createElement("canvas")
const context = canvas.getContext("2d")
const image = new Image()
const px = (number) => `${number}px`
const serialized = new XMLSerializer().serializeToString($0)
const { backgroundColor } = getComputedStyle($0.parentElement)
const blob = new Blob([serialized], {
type: `${SVG};charset=utf-8`
})
const src = URL.createObjectURL(blob)
canvas.height = HEIGHT
canvas.style.height = px(HEIGHT)
canvas.style.width = px(WIDTH)
canvas.width = WIDTH
image.addEventListener("load", () => {
const sh = parseFloat($0.getAttribute("height"))
const sw = parseFloat($0.getAttribute("width"))
let dh = 0
let dw = 0
let dx = 0
let dy = 0
// "background-size: contain" behaviour
if (sh > sw) {
dh = SCALE * sh / sw * HEIGHT
dw = SCALE * WIDTH
dx = -(dw - WIDTH) / 2
dy = 0.5 * (HEIGHT - dh)
} else {
dh = SCALE * HEIGHT
dw = SCALE * sw / sh * WIDTH
dx = 0.5 * (WIDTH - dw)
dy = -(dh - HEIGHT) / 2
}
console.log(sw, sh)
console.log(dx, dy, dw, dh)
context.fillStyle = backgroundColor
context.fillRect(0, 0, WIDTH, HEIGHT)
context.drawImage(image, dx, dy, dw, dh)
const anchor = document.createElement("a")
const href = canvas.toDataURL(PNG).replace(PNG, OCTET_STREAM)
anchor.setAttribute("download", FILENAME)
anchor.setAttribute("href", href)
anchor.setAttribute("target", "_blank")
const click = new MouseEvent("click", {
cancelable: true,
bubbles: false,
view: window
})
anchor.dispatchEvent(click)
})
image.src = src
@omarjannounn
Copy link

bro how do I use these codes, I don't have any idea about how this works but I need it asf.

@omarjannounn
Copy link

How? Provide a step by step guide please

@blocklander7258
Copy link

Uncaught TypeError: Failed to execute 'serializeToString' on 'XMLSerializer': parameter 1 is not of type 'Node'.
at :12:40 I keep getting this trying to run it in chrome

@Sakib111111
Copy link

Gggg

@Sakib111111
Copy link

Gfcvv

@Sakib111111
Copy link

Gggdbxj

@Sakib111111
Copy link

@Sakib111111
Copy link

Uploading PhotoRoom-20230605_094547.png…

@shashwat109
Copy link

unable to download, can anyone explain the procedure

@ruxinxie95
Copy link

works like a charm!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment