相关文章推荐
小百科
›
svg 转 png/jpg
svg
const
png
png转jpg
急躁的伏特加
2 年前
const
origin = location.
host
;
return
url.
indexOf
(
'data:'
) !==
0
&& url.
indexOf
(origin) <
0
; *
@param
url url -> image
const
loadImage
= url => {
return
new
Promise
(
(
resolve, reject
) =>
{
const
img =
new
Image
();
if
(
isCrossOriginUrl
(url)) { img.
crossOrigin
=
'Anonymous'
; img.
onload
=
() =>
{
resolve
(img); img.
onerror
=
function
(
) {
const
msg =
'Image load error: '
+ url;
reject
(
new
Error
(msg)); img.
src
= url; * image元素 -> base64 Data *
@param
image image node
export
const
imageToPng
= (
image: HTMLImageElement
) => {
const
canvas =
document
.
createElement
(
'canvas'
);
const
ctx = canvas.
getContext
(
'2d'
); canvas.
width
= image.
width
; canvas.
height
= image.
height
; ctx.
drawImage
(image,
0
,
0
, image.
width
, image.
height
);
return
canvas.
toDataURL
(
'image/png'
); *
@param
xml svg 的xml内容
export
const
svgToPng
=
async
(
xml: string
) => {
const
base64 =
window
.
btoa
(
unescape
(
encodeURIComponent
(xml)));
const
image64 =
`data:image/svg+xml;base64,
${base64}
`
;
const
image =
await
loadImage
(image64);
return
imageToPng
(image); *
@param
读取文件内容
export
const
readFile
= (
file, dataType =
'DataURL'
) => {
return
new
Promise
(
(
resolve, reject
) =>
{
const
reader =
new
FileReader
();
const
fnName =
`readAs
${dataType}
`
;
if
(!reader[fnName]) {
throw
new
Error
(
'File read error, dataType not support'
); reader.
onerror
=
() =>
{
reject
(
new
Error
(
'File read error'
)); reader.
onload
=
() =>
{
resolve
(reader.
result
); reader[fnName](file);
export
const
svgFile2Png
= (
file
) => {
return
readFile
(file,
'Text'
).
then
(svgToPng)
复制代码
分类:
前端
标签:
SVG
安装掘金浏览器插件
多内容聚合浏览、多引擎快捷搜索、多工具便捷提效、多模式随心畅享,你想要的,这里都有!
前往安装
炒粉兼职写代码 前端工程师 @ 字节跳动
推荐文章