近期加入了一个学校某团队一起做项目,被一个前端问题卡了好一会,浅浅记录一下

前端控制台报错如下:
在这里插入图片描述

看到Access to…立马反应到是跨域问题,没想到图片也有跨域问题(课业都是关于后端学习,前端并不是很熟悉)
以下是代码:

        <vue-cropper
          ref="cropper"
          :autoCrop="options.autoCrop"
          :autoCropHeight="options.autoCropHeight"
          :autoCropWidth="options.autoCropWidth"
          :fixedBox="options.fixedBox"
          :img="options.img"
          :info="true"
          @realTime="realTime"
        >
        </vue-cropper>

解决方案:在js中的edit函数下将图片格式转为base4即可
代码如下:

 created() {
      this.options.img = this.avatar
    },
 edit(id) {
   this.visible = true;
   this.id = id;

   this.setAvatarBase64(this.avatar, (base64) => {
     this.options.img = base64;
   });
 },
 setAvatarBase64(src, callback) {
   let _this = this;
   let image = new Image();
   image.src = src + '?v=' + Math.random();
   image.crossOrigin = "*";
   image.onload = function () {
     let base64 = _this.transBase64FromImage(image);
     callback && callback(base64);
   }
 },
 transBase64FromImage(image) {
   let canvas = document.createElement("canvas");
   canvas.width = image.width;
   canvas.height = image.height;
   let ctx = canvas.getContext("2d");
   ctx.drawImage(image, 0, 0, image.width, image.height);
   return canvas.toDataURL("image/png");
 }
Logo

前往低代码交流专区

更多推荐