0
点赞
收藏
分享

微信扫一扫

canvas绘图总结

十里一走马 2021-10-09 阅读 79

最近有个三维地图的项目,没有模型,决定先用图片顶上。但是交互的时候,发现有个问题,就是鼠标高亮某个区域时,这个效果用图片叠加的效果不是很理想。调研了一番之后,发现canvas绘图可以解决这个问题,于是,就开始研究canvas。
写的过程中遇到了窗口缩放时,位置不准的问题,在此记录,并分享给需要的人。
1.初始化

 setTimeout(function () {
        selfscope.sizeChangeSet();
      },100);
      window.onresize=function () {
        selfscope.clearCanvas();
        selfscope.sizeChangeSet();
      }

2.窗口变化时,重新定义画布的大小,图片容器的偏移量,图片容器的尺寸,图片容器的缩放比值

sizeChangeSet:function () {
      selfscope.$refs.rect.width = document.body.offsetWidth;//canvas画布宽度
      selfscope.$refs.rect.height = document.body.offsetHeight;//canvas画布高度
      selfscope.imageLeft = selfscope.$refs.model.offsetLeft;//图片距离左边的实时距离
      selfscope.imageTop = selfscope.$refs.model.offsetTop;//图片距离上边的实时距离
      selfscope.windowWidth = selfscope.$refs.model.offsetWidth;//图片实时宽度
      selfscope.windowHeight = selfscope.$refs.model.offsetHeight;//图片实时高度
      selfscope.scaleX = selfscope.windowWidth/selfscope.initWindowWidth;//图片X方向缩放比例
      selfscope.scaleY = selfscope.windowHeight/selfscope.initWindowHeight;//图片Y方向缩放比例
    }

3.通过重置canvas的高度,清除canvas绘图内容

clearCanvas:function () {//清空画布
        var c=this.$refs.rect;
        c.height=c.height;
      }

4.canvas重绘

drawRect:function(rgba,coords){//rgba是色值字符串,coords是坐标数组
//let coords = [{x:488,y:150},{x:662,y:40},{x:834,y:130},{x:648,y:250}];
        let recEle = this.$refs.rect;
        let cxt = recEle.getContext("2d");
        for(let i=0;i<coords.length;i++){
          if(i==0){
            cxt.moveTo(coords[i].x*selfscope.scaleX+selfscope.imageLeft,coords[i].y*selfscope.scaleY+selfscope.imageTop);
          }
          else {
            cxt.lineTo(coords[i].x*selfscope.scaleX+selfscope.imageLeft,coords[i].y*selfscope.scaleY+selfscope.imageTop);
          }
        }
        cxt.closePath();
        cxt.lineWidth = 0.1;
        cxt.strokeStyle = rgba;
        cxt.stroke();
        cxt.fillStyle="rgba(255,156,0,0.3)";
        cxt.fill();
      }

实现的效果如下


举报

相关推荐

0 条评论