canvas根据坐标绘制矩形

<template>
  <div class="canvas" ref="canvas-container">
    <canvas class="box" ref="canvas" :width="rateWidth" :height="rateHeight">
    </canvas>
  </div>
</template>

<script>
//rate 换算比例(以宽为换算标准)
//originWidth 原始宽
//originHeight 原始高

//rateWidth 比例换算宽
//rateHeight 比例换算高
export default {
  data(){
    return{
      rate: 1,
      originWidth: 2480, //300分辨率
      originHeight: 3508, //300分辨率
      dots:[],
    arrs:[
     [{x:19,y:85},{x:111,y:85},{x:111,y:163},{x:19,y:163},{x:19,y:85}],
      ]

    }
  },
  computed:{
    rateWidth(){
      return this.originWidth * this.rate
    },
    rateHeight(){
      return this.originHeight * this.rate
    }
  },
  mounted(){
    this.getarrs()
    this.calcRate()
  },
  methods:{
        getarrs(){
            let dots = this.arrs
          dots.forEach(item=>{
            item.forEach(it=>{
              it.x = it.x * this.rate
              it.y = it.y * this.rate
            })
          })
          this.dots = dots
          this.$nextTick(()=>{
            this.initCanvas()
          })
        },
    calcRate(){
      let containerDom = this.$refs['canvas-container']
      const containerWith = containerDom.clientWidth || containerDom.offsetWidth
      const rate = Math.floor(containerWith / this.originWidth *100) / 100
      this.rate = rate
    },
    initCanvas(){
      let canvasDom = this.$refs['canvas']
      let ctx = canvasDom.getContext("2d")
      this.dots.forEach(item=>{
        for(let i=0; i < item.length; i++){
          if(i == item.length-1) return 
          ctx.beginPath();
          ctx.moveTo(item[i].x,item[i].y);
          ctx.lineWidth = 2
          ctx.lineTo(item[i+1].x,item[i+1].y)
          ctx.stroke();
          ctx.storkeStyle = '#ff0000'
        }
      })
    }
  }
}
</script>

<style  scoped>
.canvas{
  box-sizing: border-box;
  padding: 10px;
  width: 100%;
  display: flex;
  justify-content: center;
  border: 1px solid red
}
.box{
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
</style>

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值