实现目标:
1. 了解雪碧图是什么
2. 用我自己做的一个小工具为本地发布的地图服务制作一个雪碧图!
关键词:雪碧图 mapbox地图服务 electron react canvas typescript
什么是雪碧图?
首先它的英文名叫做“Sprite Images”,翻译过来就叫做雪碧图了,当时第一反应和喝的雪碧有什么关系,原来是翻译过来的,也可以叫做精灵图,至于为什么这么叫,我也不知道。它就是将很多图像图标合并到一个大图片中,然后有一个“小伙伴“”(文件)来记录每一个小图片的大小,在大图中的位置。在使用的时候就可以根据位置和大小来显示小图标了。就像下面这样。看这张动图就明白了它的原理了
雪碧图产生的意义?
雪碧图的产生要从网页技术说起,大家都知道我们网页上的图片资源都是通过http向服务器请求加载到浏览器上的,当页面上使用了很多小图片的时候,每一张都需要发起一次http请求,下图是一次完整的网页请求渲染过程,一次请求图片也要前4步,多多少少也会消耗资源的,雪碧图的优势是减少了http请求的次数,缓解了请求压力。请看2-4步骤
雪碧图的缺点
雪碧图也有缺点, 其缺陷在于小图标在高清屏幕上可能会失真,另外频繁使用定位会占用比较多的CPU
用electron实现一个雪碧图生成工具
进入今天的正题,带领大家使用electron react canvas 这些技术实现一个简单的雪碧图桌面工具。首先看下实现的界面图:
界面效果
首先这个工具是一个桌面工具,是用electron+react+typescript实现。图形拼接是使用的canvas。项目已经开源到github上面:https://github.com/mjcc007/csprite_make
对于前端开发的朋友来说,react和ts大家都非常熟悉,electron肯定也耳有所闻。这里就简单介绍下electron:Electron是由Github开发,用HTML,CSS和JavaScript来构建跨平台桌面应用程序的一个开源库。 Electron通过将Chromium和Node.js合并到同一个运行时环境中,并将其打包为Mac,Windows和Linux系统下的应用来实现这一目的。如何使用:
开发工具使用的是vscode
- step1: 克隆本项目到本地
- step2: npm install
- step3: npm run wepack_watch 起来后 F5进入debug,即可看见启动界面
- step4: npm run webpack_build && npm run compile_win32 可以编译成window版本
详细可以查看package.json里的script
{
"scripts": {
"webpack_watch": " ts-node --transpile-only --project scripts/tsconfig.json scripts watch",
"webpack_build": " ts-node --transpile-only --project scripts/tsconfig.json scripts build",
"compile_dir": " ts-node --transpile-only --project scripts/tsconfig.json scripts compile_dir",
"compile_win32": "ts-node --transpile-only --project scripts/tsconfig.json scripts compile_win32",
"compile_darwin": "ts-node --transpile-only --project scripts/tsconfig.json scripts compile_darwin",
"compile_linux": " ts-node --transpile-only --project scripts/tsconfig.json scripts compile_linux"
},
}
关键代码
private drawSprite () {
this.initCanvas(this.m_SpriteImgInfo.width, this.m_SpriteImgInfo.height)
let curHeight = 0
for (let row = 0, totalRows = this.m_LayoutList.length; row < totalRows; row++) {
let curWidth = 0
for (let column = 0, totalColumns = this.m_LayoutList[row].length; column < totalColumns; column++) {
let curImg:ImageObj = this.m_LayoutList[row][column]
this.m_ctx.drawImage(curImg.imgObj, curWidth, curHeight)
this.m_SpriteImgInfo.positionJson[curImg.imgInfo.name] = {
x: curWidth,
y: curHeight,
width: curImg.imgInfo.width,
height: curImg.imgInfo.height,
pixelRatio: 1,
sdf: false
}
curWidth += curImg.imgInfo.width
}
curHeight += Math.max.apply(Math, this.m_LayoutList[row].map((o) => {return o.imgInfo.height}))
}
this.m_SpriteImgInfo.imgSrc = this.m_canvas.toDataURL("image/png")
this.m_isSuccess = true
store.spriteStore.setSpriteImg(this.m_SpriteImgInfo.imgSrc)
// ipcRenderer.send('savesprite', this.m_SpriteImgInfo)
}
这样就可以使用自己自作的雪碧图在地图上显示了。可以让ui设计各种漂亮的图标放到地图中了。
参考链接:
https://www.modpagespeed.com/doc/filter-image-sprite
https://www.cnblogs.com/ATtuing/p/9273391.html
本人菜鸟码农一枚,文章中如有不妥之处,欢迎留言指正。最后推荐一下本人的服务号和订阅号。关注公众号回复获取“electron入门教程”获取一套个人收藏的electron视频教程 。
网友评论