当前位置: 移动技术网 > IT编程>开发语言>JavaScript > vue canvas绘制矩形并解决由clearRec带来的闪屏问题

vue canvas绘制矩形并解决由clearRec带来的闪屏问题

2019年09月06日  | 移动技术网IT编程  | 我要评论

起因:在cavnas绘制矩形时 鼠标移动一直在监测中,所以鼠标移动的轨迹会留下一个个的矩形框,

要想清除矩形框官方给出了ctx.clearrect() 但是这样是把整个画布给清空了,因此需要不断

向画布展示新的图片,这样就出现了不断闪屏的问题。

那么怎么解决呢?

提供了技术,可以点击看看这边文章。

具体就是画图的时候做两个canvas层,一个临时层 一个显示层,鼠标的监听事件放在显示层处理,

每次清空的时候只清空临时层,这样就可以解决闪屏问题了。

  部分代码如下:

<!--临时层-->
<canvas id="custompositionimg2" ref="table2"  style=" display:none;"></canvas>
<!--显示层 增加鼠标按下,移动,松开事件-->
<canvas id="custompositionimg" ref="table"  @mousedown="mousedown" @mousemove="mousemove" @mouseup="mouseup" style=""></canvas>

显示层展示图片:

//因为项目是dialog展示自定义画板,所以图片展示就写在了dialog打开的钩子里,如果需要直接复制
vue.nexttick里面的代码就行
show () {
   vue.nexttick(_ => {
     let customcanvas =this.$refs.table;// canvas显示层
     this.customstyle ='';
     customcanvas.height = 740;
     customcanvas.width = 1460;
     this.customcxt = customcanvas.getcontext("2d");
     let img = new image();
     img.src = this.imgsrc;
     let that = this;
     img.onload = function () {
       that.customrwidth = customcanvas.width / img.width; //原图与展示图片的宽高比
       that.customrheight = customcanvas.height / img.height;
       that.customcxt.drawimage(img, 0, 0, customcanvas.width, customcanvas.height); 
     };

   })

},

鼠标操作事件

//鼠标按下时执行
mousedown(e){
  this.ismousedownincanvas = true;
  // 鼠标按下时开始位置与结束位置相同 防止鼠标在画完矩形后 点击图画形成第二个图形
  this.endx = e.offsetx;
  this.endy = e.offsety;
  this.startx = e.offsetx;
  this.starty = e.offsety;

},
//鼠标移动式时执行
mousemove(e){
  if (this.ismousedownincanvas){ // 当鼠标有按下操作时执行
    console.log( e.offsetx,e.offsety);
    if((this.endx != e.offsetx)||( this.endy != e.offsety)){
      this.endx = e.offsetx;
      this.endy = e.offsety;
      let wwidth = this.endx - this.startx;
      let wheigth = this.endy - this.starty;
      let tempcanvas = this.$refs.table2; // canvas临时层
      let tempctx = tempcanvas.getcontext('2d');
      tempcanvas.width = 1460; tempcanvas.height = 740; // 设置宽高
      // 清除临时层指定区域的所有像素
      tempctx.clearrect(0, 0, 1460, 740);
      // 重新展示图片
      let img = new image();
      img.src = this.imgsrc;
      let that = this;
      img.onload = function () {
        that.customcxt.drawimage(img, 0, 0,1460, 740);
      };
      this.customcxt.strokestyle=" #00ff00"; //矩形框颜色
      this.customcxt.linewidth="2"; //矩形框宽度
      this.customcxt.strokerect(this.startx,this.starty,wwidth,wheigth); //绘制矩形
    }else{
        //鼠标按下静止时显示矩形的大小。
      let wwidth2 = this.endx - this.startx;
      let wheigth2 = this.endy - this.starty;
      this.customcxt.strokerect(this.startx,this.starty,wwidth2,wheigth2)
    }
  }
},
//鼠标松开时执行
mouseup(e){
  this.ismousedownincanvas = false;
  // 绘制最终的矩形框
  let wwidth = this.endx - this.startx;
  let wheigth = this.endy - this.starty;
  this.customcxt.strokerect(this.startx,this.starty,wwidth,wheigth)
},

总结

以上所述是小编给大家介绍的vue cavnas绘制矩形并解决由clearrec带来的闪屏问题,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网