<template>
  <div>
    <button type="button" class="btn btn-warning" @click="error1">错误</button>
    <button @click="word1()">文字</button>
    <button @click="restuya()">清除批注</button>
    <button @click="back()">回退</button>
    <button @click="saveTu()">保存</button>
    <hr>
    <img id="canvasImg" src="./../../assets/404_images/404.png" style="display: none">
    <div style="position: relative;">
      <canvas id="canvas" width="700"  height="500" >
        您的浏览器不支持绘图，请升级或更换浏览器！
      </canvas>
      <input type="text" value="" class="hide" id="txt" placeholder="请输入文字">
      <textarea class="hide" id="word" cols="30" rows="10"  placeholder="请输入文字" autofocus></textarea>
      <input id="inputV" type="hidden"  value="1">
      <span>保存的图片</span>
      <div id="res"></div>
    </div>

  </div>
</template>
<script>
  let preDrawAry = [];
  let img = new Image();
  export default {
    data() {
      return {
        canvas:null,
        ctx:null,
        myCanvas_rect:null,
        Txt:null,
        word:null,
        widths:0,
        heights:0,
        lineW:3,
        colorF:"#e42343",
        imgData:'',
      }
    },
    mounted(){
      let _this=this;
      preDrawAry = [];
      let canvas = document.getElementById('canvas');
      this.canvas = document.getElementById('canvas');
      this.ctx = canvas.getContext('2d');
      this.myCanvas_rect = this.canvas.getBoundingClientRect();
      this.Txt = document.getElementById('txt');
      this.word = document.getElementById('word');
      this.widths = this.myCanvas_rect.width;
      this.heights = this.myCanvas_rect.height;
      setTimeout(function(){
        _this.draw();
      },1000)
/*
      this.ctx .clearRect(0, 0, 700, 500);
      let imgs = new Image();
      imgs.src ="./../../assets/404_images/404.png";
      setTimeout(function(){
        this.draw();
        this.ctx.drawImage(imgs,0,0,700,500);
      },1000)*/
     /* imgs.onload=function(){
        this.ctx.drawImage(imgs,0,0,700,500);
        this.ctx.closePath();

        let pattern=this.ctx.createPattern(imgs,"no-repeat")//不加；号
        this.ctx.fillStyle=pattern;
        this.ctx.fillRect(0,0,700,500);
      }*/

    },
    methods: {
      draw(){
        debugger;
        let canvasImg = document.getElementById("canvasImg");
        canvasImg.style.width = '700px';
        canvasImg.style.height = '500px';
        this.ctx.drawImage(canvasImg,0,0,700,500);
      },
      // 叉号
      error1(){
        let canvas1 = document.getElementById('canvas');
        let ctx1 = canvas1.getContext('2d');
        this.Txt.style.display="none";
        this.word.style.display="none";
        ctx1.closePath();
        canvas1.onmousedown=function () {
          this.imgData= ctx1.getImageData(0,0,canvas1.width,canvas1.height);
          preDrawAry.push(this.imgData);
          ctx1.beginPath();
          ctx1.strokeStyle = "#e42343";
          ctx1.lineWidth = "3";
          ctx1.lineJoin="round";
        };
        //鼠标按下的位置
        canvas1.onmouseup=function (ev) {
          let oldX = ev.offsetX;
          let oldY = ev.offsetY;
          ctx1.moveTo(oldX,oldY);
          ctx1.lineTo(ev.offsetX+10,ev.offsetY+10);
          ctx1.moveTo(ev.offsetX+10,ev.offsetY);
          ctx1.lineTo(ev.offsetX,ev.offsetY+10);
          ctx1.stroke();
        };
        this.ctx.closePath();
      },

      // 文字先写字
      text(){
        let canvas2 = document.getElementById('canvas');
        let ctx2 = canvas2.getContext('2d');
        let Txt2 = document.getElementById('txt');
        Txt2.style.display="block";
        this.word.style.display="none";
        ctx2.font="16px Microsoft Yahei";
        canvas2.onmousedown=function (ev) {
          this.imgData=ctx2.getImageData(0,0,canvas2.width,canvas2.height);
          preDrawAry.push(this.imgData);
          var v = Txt2.value;
          //            console.log(v);
          if (v != '') {
            var oldX = ev.offsetX;
            var oldY = ev.offsetY;
            // console.log(oldX,oldY);
            ctx2.moveTo(oldX,oldY);
            canvas2.onmouseup=function () {
              ctx2.fillStyle=this.colorF;
              ctx2.fillText(v,oldX,oldY);
              canvas2.TextAutoLine(v,canvas2,oldX,oldY,20);
              // Txt.value = "";
              Txt2.style.display="none";
            }
          }
        }
      },

      // 文字
      word1(){
        let canvas3 = document.getElementById('canvas');
        let ctx3 = canvas3.getContext('2d');
        let Txt3 = document.getElementById('txt');
        let word3 = document.getElementById('word');
        Txt3.style.display="none";
        ctx3.font="16px Microsoft Yahei";
        canvas3.onmousedown=function () {
          ctx3.closePath();
        }
        canvas3.onmouseup=function (ev) {
          var inputV= document.getElementById('inputV').value;
          if(inputV == 1){
            document.getElementById('word').focus();
            //               console.log(ev.offsetX,ev.offsetY);
            var oldX = ev.offsetX;
            var oldY = ev.offsetY;
            word3.style.display="block";
            word3.style.left=oldX+'px';
            word3.style.top =oldY+'px';

            word3.onblur=function () {
              let v = word3.value;
              if(v != '' && v != ' '){
                this.imgData=ctx3.getImageData(0,0,canvas3.width,canvas3.height);
                let img = ctx3.getImageData(0,0,canvas3.width,canvas3.height);
                debugger;
                preDrawAry.push(img);
                ctx3.moveTo(oldX,oldY);
                ctx3.fillStyle="#e42343";
                let lineWidth = 0;
                let canvasWidth = canvas3.width;
                let lastSubStrIndex= 0;
                for(let i=0;i<v.length;i++){
                  lineWidth+=ctx3.measureText(v[i]).width;
                  if(lineWidth>canvasWidth-oldX){
                    ctx3.fillText(v.substring(lastSubStrIndex,i),oldX,oldY);
                    oldY+=20;
                    lineWidth=0;
                    lastSubStrIndex=i;
                  }
                  if(i==v.length-1){
                    ctx3.fillText(v.substring(lastSubStrIndex,i+1),oldX,oldY);
                  }
                }
                inputV ="2";
                word3.value = "";
              }
            }
          }
        }
      },

      // 文字过长超出换行toDataURL()
      canvasTextAutoLine(str,canvas,initX,initY,lineHeight){
        let ctx = canvas.getContext("2d");
        let lineWidth = 0;
        let canvasWidth = canvas.width;
        let lastSubStrIndex= 0;
        for(let i=0;i<str.length;i++){
          lineWidth+=ctx.measureText(str[i]).width;
          if(lineWidth>canvasWidth-initX){
            ctx.fillText(str.substring(lastSubStrIndex,i),initX,initY);
            initY+=lineHeight;
            lineWidth=0;
            lastSubStrIndex=i;
          }
          if(i==str.length-1){
            ctx.fillText(str.substring(lastSubStrIndex,i+1),initX,initY);
          }
        }
      },

      // 删除批注
      restuya(){
        this.word.style.display="none";
        this.Txt.style.display="none";
        this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
        window.location.reload();
      },

      // 撤销
      back(){
        this.word.style.display="none";
        this.Txt.style.display="none";
        if(preDrawAry.length>0) {
          var popData = preDrawAry.pop();
          this.ctx.putImageData(popData, 0, 0);
        }
      },

      // 回退一次
      put(){
        this.ctx.putImageData(this.imgData,0,0);
      },

      //保存
      saveTu(){
        let canvas = document.getElementById('canvas');
        var image = new Image();
        image = canvas.toDataURL('image/png');
        document.getElementById('res').innerHTML = '<img style="border: 1px solid #666666;" src="'+image+'">';
        console.log(image);
        debugger;
        /*img.setAttribute('crossOrigin', 'Anonymous') ;// 解决某些图片跨域（有些图片仍不可使用)
        img.src = 'url';
        img.onload = (imgs) => {
          let base64 = this.setBase64(imgs);
          var arr = base64.split(',');
          var mime = arr[0].match(/:(.*?);/)[1] ;// 获取图片的类型 （image/jpg)
          var bstr = atob(arr[1]); // 将base64转码
          var n = bstr.length ;// 获得转码长度
          var u8arr = new Uint8Array(n); // 获得length个为0的数组
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n) // 获得unicode码
          }
          this.file = new File([u8arr], 'faceImg', { type: mime }); // 生成文件
          console.log(this.file);
          this.url = base64
        }*/
      },
       setBase64(img) {
        let ctx = document.createElement('canvas');
        const c = ctx.getContext('2d');
        ctx.width = img.path[0].width;
        ctx.height = img.path[0].height;
        c.drawImage(img.path[0], 0, 0, img.path[0].width, img.path[0].height);
        let ext = img.src
          .substring(img.src.lastIndexOf('.') + 1)
          .toLowerCase(); // 获取图片后缀
        let url = ctx.toDataURL(`image/${ext}`);
        return url
      }
    }
  }
</script>

<style scoped>
  canvas{
    border:1px solid #000000;
    cursor: crosshair;
  }
  .hide{
    display: none;
  }
  #txt{
    position: absolute;
    top: 1%;
    left: 1%;
    width: 575px;
    height: 30px;
    border:1px solid #e42343;
  }
  #word{
    position: absolute;
    width: 220px;
    height: 80px;
    padding: 0 2px;
    background:none;
    color:#e42343;
    border: 1px dashed #b9b9b9;
  }
  #word::-webkit-input-placeholder{
    color:#e42343;
  }
  #word::-moz-placeholder{
    color:#e42343;
  }
  #word::placeholder{
    color:#e42343;
  }
  #res{
    display: inline-block;
  }
</style>
