Created
February 25, 2021 12:12
-
-
Save revenkroz/551537b0944ebd1bbf79ecf73148c627 to your computer and use it in GitHub Desktop.
Script to get an image (see selector) with rounded borders
This file contains hidden or 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
(() => { | |
function roundedImage(x, y, width, height, radius) { | |
ctx.beginPath(); | |
ctx.moveTo(x + radius, y); | |
ctx.lineTo(x + width - radius, y); | |
ctx.quadraticCurveTo(x + width, y, x + width, y + radius); | |
ctx.lineTo(x + width, y + height - radius); | |
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height); | |
ctx.lineTo(x + radius, y + height); | |
ctx.quadraticCurveTo(x, y + height, x, y + height - radius); | |
ctx.lineTo(x, y + radius); | |
ctx.quadraticCurveTo(x, y, x + radius, y); | |
ctx.closePath(); | |
} | |
const image = document.querySelector('.show-logo img'); | |
const canvas = document.createElement('canvas'); | |
const ctx = canvas.getContext('2d'); | |
const defaultWidth = 600; | |
const borderRadius = 24; | |
const scale = defaultWidth / image.width; | |
canvas.width = defaultWidth; | |
canvas.height = image.height * scale; | |
ctx.fillStyle = '#fff'; | |
ctx.fillRect(0, 0, canvas.width, canvas.height); | |
const img = new Image(); | |
img.setAttribute('crossorigin', 'anonymous'); | |
img.onload = () => { | |
ctx.save(); | |
roundedImage(0, 0, defaultWidth, image.height * scale, borderRadius); | |
ctx.clip(); | |
ctx.drawImage(img, 0, 0, defaultWidth, image.height * scale); | |
ctx.restore(); | |
window.open().document.write('<img src="' + canvas.toDataURL() + '" />'); | |
} | |
img.src = image.src; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment