用 3Dmol.js 在 html 和 markdown 中插入结构模型
可互动的结构模型可以让网页文章变得更为生动,写在笔记里也可以更为方便地随时查看模型的细节。之前使用过 JSmol 来实现这个功能,今天来尝试一下更为轻量化的 3Dmol.js[1]
结构文件格式的转换
3Dmol.js 支持的文件格式包括 pdb, sdf, mol2, xyz, cube
如果手里的文件是其他格式,可以通过 ase 来进行转换。命令行运行如下即可:
$ ase convert CONTCAR out.pdb
拿到的结构文件可以放在博文或者笔记的路径里,也可以转换成一个 string 直接粘贴进 html/md 文件里,如此就可以轻松到处迁移(本文采取此办法)。注意这个 string 需要包含\n
换行符,可以用 awk
命令来转换:
$ awk '{printf "%s\\n", $0}' out.pdb | sed "s/'/\\\'/g"
在 html 里插入结构模型
首先,从 url 导入最新稳定版本的 3Dmol.js
<script src="https://3Dmol.csb.pitt.edu/build/3Dmol-min.js"></script>
创建 container,定义大小位置
<div id="container-01" class="mol-container"></div>
<style>
.mol-container {
width: 75%;
height: 400px;
position: relative;
}
</style>
接下来运行 3Dmol.js 生成组件。这里可以自定义背景颜色、原子渲染风格(sphere/stick/line/cross/cartoon/clicksphere)、晶格显示与否。记得要把addModel
的第一个参数(笔者随手写了个 CO2 的 xyz 举例)替换为自己的结构 string ,并且给出文件的格式
<script>
$(function() {
let element = $('#container-01');
let config = { backgroundColor : 'white' };
let viewer = $3Dmol.createViewer( element, config );
viewer.addModel("3\n\nC 0 0 0\nO 1.16 0 0\nO -1.16 0 0", "xyz");
viewer.addUnitCell();
viewer.setStyle({}, {sphere : {}});
viewer.zoomTo();
viewer.render();
});
</script>
把上面这段放在 html 里就可以使用了,十分方便。
互动方式为:滚轮/右键拖拽=缩放,左键拖拽=旋转,ctrl+左键拖拽=平移
在 markdown 里插入结构模型
直接把上面的 html 代码块放进 md 文件即可,别忘了声明 html 环境
<html>
<上面的 html 代码块>
<html>
插入到笔者个人网站的 post 里看看效果。
首先是一个分子结构,NiPc(OMe)4*COOH 反应中间体[2]:
再看一个周期性体系,B-rich WB (001) 的重构表面[3]:
效果应该说是比较棒的,如果再仔细调整一下渲染的各个选项、参数,还可以更 fancy。
感兴趣的读者可以去看看 3Dmol.js 的 documentation[4],动手实践一下。
参考
- ^3Dmol.js Official Website https://3dmol.csb.pitt.edu/
- ^Zhang, X. ; Wang, Y. ; Gu M. ; Wang, M. ; Zhang, Z.; Pan, W.; Jiang, Z.; Zheng, H; Lucero, M.; Wang, H.; Sterbinsky, G.; Ma, Q.; Wang, Y-G.*;, Feng, Z.*; Li, J.; Dai, H.; Liang, Y.* Molecular Engineering of Dispersed Nickel Phthalocyanines on Carbon Nanotubes for Selective CO2 Reduction. 2020, Nature Energy, 5, 684-692 https://zishengz.github.io/2020/08/20/natene/
- ^Zhang, Z.; Cui, Z-H.; Jimenez-Izal, E.; Sautet, P.*; Alexandrova, A. N.* Hydrogen Evolution on Restructured B-rich WB: Metastable Surface States and Isolated Active Sites. 2020, ACS Catalysis, accepted. DOI: 10.1021/acscatal.0c03410 https://zishengz.github.io/2020/11/16/acscatal/
- ^3Dmol.js Documentation https://3dmol.csb.pitt.edu/doc/index.html