class CanvasImage { /** * 初始化类 * * @param {[object]} el canvas所在的容器 * @param {[object]} option 配置项 * * @return {[object]} canvasImage实例化对象 */ constructor(el, option) { this.el = el; this.option = option; this.cvs = ""; this.ctx = ""; this.width = 100; this.height = 100; // 初始化内容 this.init(el, option); } init(el, option) { // 设置容器的宽高 this.setWidth(option); this.setHeight(option); // 生成canvas容器和canvas this.createElement(el); } createElement(el) { // 生成容器 const ctn = document.createElement('div'); ctn.style.width = "100%"; ctn.style.height = "100%"; // 生成canvas const cvs = document.createElement('canvas'); cvs.width = this.width; cvs.height = this.height; cvs.style.width = "100%"; cvs.style.height = "100%"; cvs.style.objectFit = "contain"; this.cvs = cvs; this.ctx = cvs.getContext('2d'); // 添加canvas ctn.appendChild(cvs); // 添加容器 el.appendChild(ctn); } /** * 设置canvas的宽度 * * @param {[type]} option 配置项 * * @return {[type]} 无 */ setWidth(option) { if(typeof option == 'object' && typeof option.width != 'undefined') { this.width = option.width; }else { this.width = 100; } } /** * 设置canvas的高度 * * @param {[type]} option 配置项 * * @return {[type]} 无 */ setHeight(option) { if(typeof option == 'object' && typeof option.height != 'undefined') { this.height = option.height; }else { this.height = 100; } } } export default CanvasImage;