Created
September 28, 2018 07:33
-
-
Save shinriyo/c217b7155b6ef2b68405ac2696d56074 to your computer and use it in GitHub Desktop.
SVGで色を無理やり付ける(IE, Edge) TypeScript
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
/** | |
* SVGで色を無理やり付ける(IE, Edge). | |
* | |
* @param {*} name | |
* @param {*} elem | |
* @param {*} fillColor | |
* @returns {void} | |
*/ | |
export const paintSVG = (name: string, elem: any, fillColor: any): void => { | |
let a = '99'; | |
let b = '99'; | |
let c = '800'; | |
let d = '800'; | |
let colorBlock = Object.assign( | |
document.createElement('img'), | |
{ | |
/* | |
<svg xmlns="http://www.w3.org/2000/svg" | |
xmlns:xlink="http://www.w3.org/1999/xlink" width="100" heigh="100" | |
preserveAspectRatio="xMinYMid meet"> <rect x="0" y="0" width="300" height="300" fill="mistyrose"/> | |
</svg> | |
を以下のサイトで変換. | |
Edge, IEはちゃんとbase64変換しないと動作しない. | |
widthとheightは必須. | |
※mistyroseは色の例、#FFFFFFのような指定もできる. | |
CSSプロパティのところ. | |
http://blog.s0014.com/posts/2017-01-19-il-to-svg/ | |
*/ | |
src: 'data:image/svg+xml;charset=utf8,%3Csvg%20xmlns%3D%22' | |
+ 'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20' | |
+ 'width%3D%22' + a + '%22%20heigh%3D%22' + b + '%22%20preserveAspectRatio' | |
+ '%3D%22xMinYMid%20meet%22%3E%20%3Crect%20x%3D%220%22%20y%3D%220%22%20' | |
+ 'width%3D%22' + c + '%22%20height%3D%22' + d + '%22%20fill%3D%22' | |
+ fillColor + '%22%2F%3E%3C%2Fsvg%3E', | |
className: 'color-block' | |
} | |
); | |
if (elem === null) { return; } | |
let pos = ''; | |
if (name === 'ie') { | |
// IE | |
pos = elem.currentStyle.position; | |
} else { | |
// IE以外(React、TypeScript経由のせいかコレでも動作した) | |
pos = window.getComputedStyle(elem).getPropertyValue('position'); | |
} | |
if (pos === 'static') { | |
elem.style.position = 'relative'; | |
} | |
elem.appendChild(colorBlock.cloneNode(true)); | |
}; |
Author
shinriyo
commented
Nov 9, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment