<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>
    <button @click="takePhoto()">拍照</button>
    <el-form
      style="width: 700px;"
      label-width="100px"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="test" placeholder="名称"/>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="limitedPhoto" title="人脸登录">
      <div class="testTracking">
        <faceLogin name="faceLogin" @func="getMsgFormSon"></faceLogin>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import faceLogin from '@/views/testModel/faceLogin'
  let preDrawAry = [];
  // let img = new Image();
  export default {
    components:{
      faceLogin
    },
    data() {
      return {
        canvas:null,
        ctx:null,
        myCanvas_rect:null,
        Txt:null,
        word:null,
        widths:0,
        heights:0,
        lineW:3,
        colorF:"#e42343",
        imgData:'',
        limitedPhoto:false,
        test:''
      }
    },
    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)
    },
    methods: {
      getMsgFormSon(data){
        this.limitedPhoto = data;
      },
      takePhoto(){
        this.limitedPhoto = true;
      },
      takeClick(){
        let canvas = document.getElementById("myCanvas");
        let context = canvas.getContext('2d');
        let video = document.getElementById("myVideo");
        context.drawImage(video,0,0,90,68);
        let image = new Image();
        image = canvas.toDataURL('image/png');
        document.getElementById('res').innerHTML = '<img src="'+image+'">';
        let imgData = {base64:image};
        faceLogin(imgData).then((res) => {
          if (res.code >= 200) {
            this.$message.success("成功");
          }
        });
      },
      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+'">';
      },
       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>
