最近在做商品详情的时候,有这样一个需求:用户可以使用富文本编辑器编辑商品,并且在小程序中可以展示。然鹅,小程序并不支持HTML标签,webview组件也只能加载URL,这就捉鸡了。 最终决定采用将富文本内容转化为图片,后台保存转化后的图片与HTML内容,这样就可以实现在小程序中展示的富文本内容,同时又可以让用户随时修改商品介绍的内容了。 这里我们用到的富文本编辑器插件为Simditor,选择它的原因很简单,风格和我们的整体风格符合。HTML转换图片采用html2canvas。贴一段项目的代码:
var editor = null;function initSim(p) { editor = new Simditor({ textarea:$("#designer"), toolbar:['title', 'bold', 'italic', 'underline', 'strikethrough', 'fontScale', 'color', '|', 'ol', 'ul', 'blockquote', 'code', 'table', '|', 'link', 'image', 'hr', '|', 'indent', 'outdent', 'alignment'], upload:{ url:"文件上传地址",//这里我们修改了Simditor源码,符合我们项目的规则, //Simditor貌似只生成对上传图片的引用的image,标签PHP代码
$base64_img = urldecode(trim(input('file'))); $up_dir = 'uploads/'; if(!file_exists($up_dir)) { mkdir($up_dir,0777); } if(preg_match('/^(data:s*image/(w+);base64,)/',$base64_img,$result)) { $type = $result[2]; if(in_array($type,array('pjepg','jpeg','jpg','gif','bmp','png'))) { $saveName = $this->request->time().randomkeys(6).".".$type; if(file_put_contents($up_dir.$saveName,base64_decode(str_replace($result[1],'',$base64_img)))) { return $this->ret->setCode(0)->setMsg($this->request->root().'/'.$up_dir.$saveName)->toJson(); }else { return $this->ret->setCode(1)->setMsg("文件上传失败")->toJson(); } }else { return $this->ret->setCode(1)->setMsg("图片上传类型错误")->toJson(); } }else { return $this->ret->setCode(1)->setMsg("文件错误")->toJson(); }



