CKEditor自定义按钮,找了很多篇教程,都说的不清不楚的,现参考官方文档,在此记录下开发过程。

官网文档:https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_plugins.html

Demo:http://www.ihtmlcss.com/demo/CKEditor/

1.在CKEditor的plugins下新建目录uploadImg,目录结构如下:

文件夹名、图标名、插件名保持一致,这里我将要添加的插件叫: uploadImg

2.接下来编辑plugin.js

// 压缩图片的方法
function $imgCompressor(file,maxLength,quality){
  if(!file || typeof file != 'object' || !file.type || file.type.indexOf('image')<0) {
    return new Promise((resolve,reject)=>{
      resolve(new Error('simplify-img-compressor:必须传入图片类型的文件对象'));
    });
  } else {
    let maxImgLength = maxLength?maxLength:1200;// 最长边的长度最大值
    let qua = quality?quality:0.6;// 压缩质量
    let reader = new FileReader();
    let compressImg = new Image();
    reader.readAsDataURL(file);
    return new Promise((resolve,reject) => {
      reader.onload = function(e) {
        let newUrl = e.target.result;
        let c = document.createElement('canvas');
        let img = document.createElement('img');
        img.src = newUrl;
        let ctx=c.getContext("2d");
        let timmer = setInterval(function(){
          if(reader.readyState == 2) {
            clearInterval(timmer);
            let imgHeight = img.height;
            let imgWidth = img.width;
            if(imgHeight>maxImgLength || imgWidth > maxImgLength) {
              if(imgHeight>imgWidth) {
                let rate = maxImgLength / imgHeight;
                imgHeight = maxImgLength;
                imgWidth = imgWidth*rate;
                c.width = imgWidth;
                c.height = imgHeight;
              } else {
                let rate = maxImgLength / imgWidth;
                imgWidth = maxImgLength;
                imgHeight = imgHeight*rate;
                c.width = imgWidth;
                c.height = imgHeight;
              }
            } else {
              c.width = img.width;
              c.height = img.height;
            }
            ctx.drawImage(img,0,0,imgWidth,imgHeight);
            compressImg = c.toBlob(function(blob){
              resolve({
                file:blob,
                name:file.name,
                quality:qua,
                maxImgLength:maxImgLength,
                afterCompressorSize:(blob.size/1024).toFixed(2) + 'kb',
                beforeCompressorSize:(file.size/1024).toFixed(2) + 'kb',
                dataURL:c.toDataURL(),
              });
            },file.type,qua);
          }
        },200);
      };
    });
  }
}
// 注册插件
CKEDITOR.plugins.add( 'uploadImg', { // 注册名为uploadImg的插件
	icons: 'uploadImg',// 按钮的图标名
	init: function( editor ) {
		editor.addCommand( 'insertUploadImg', {
			exec: function( editor ) {
                        // 此处定义点击按钮时的行为
                        // 此实例实现的功能是压缩所选择的图片并上传到服务器,然后将返回的内容添加到编辑器里
				var $fileInput = document.createElement('input');
				$fileInput.type = 'file';
				$fileInput.accept = 'image/*';
				$fileInput.click();
				$fileInput.addEventListener('change',function(e){
					var fileList = e.target.files;
					console.log(fileList);
					if(fileList.length>0) {
						$imgCompressor(fileList[0],100,0.6).then((res)=>{
let formData = new FormData();
formData.append('file',res.file,res.name);
//创建异步对象
let xhr = new XMLHttpRequest();
xhr.open('post', 'http://www.ihtmlcss.com/phpcrm/tp5/public/index.php/admin/uploader/uploadPublic',true);
xhr.send(formData);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
let result = xhr.responseText;
if(typeof result == 'string') {result = JSON.parse(result)}
editor.insertHtml( "<p><img src='http://www.ihtmlcss.com/phpcrm/tp5/public/index.php/"+result.obj.fileUrl+"'/></p>" );
} else {
alert('上传失败');
}
};
}); } }) } }); // 添加按钮到编辑器 editor.ui.addButton( 'uploadImg', { label: 'Insert uploadImg', command: 'insertUploadImg', toolbar: 'insert' }); } });

3.初始化编辑器前先启用插件

<textarea id="content" name="content"></textarea>
<script>
    CKEDITOR.plugins.addExternal('uploadImg', '/plugins/CKEditor/plugins/uploadImg/', 'plugin.js');
    var updateCKEditor = CKEDITOR.replace( 'content', {
        extraPlugins: ['uploadImg'],
    } );
</script>

4.如果你使用了config.js来配置工具栏,则需要手动将插件添加到此处

CKEDITOR.editorConfig = function( config ) {
	// Define changes to default configuration here. For example:
	config.language = 'zh-cn';
	config.uiColor = '#f5f5f5';
	config.height = 300;
    config.toolbar_Basic =
        [
            ['Source','Image','uploadImg']
        ];
    config.toolbar = 'Basic';
};

总结:

1.插件名、文件夹名、按钮名保持一致

2.实例中的插入图片功能还必须引入编辑器中的Image插件,否则插入图片功能会不正常