Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

在一个canvas上再绘制叠加一个canvas,报错,如下图和代码

问题

我想把红块,放到人物框内

1604044523(1).png

image.png

代码

<template>
  <div class='box'>
    <canvas id="canvas"
            class='canvas'></canvas>
    <canvas id="canvas2"
            class='canvas2'></canvas>
    <img src="../../assets/woman.png"
         alt=""
         style='display:none'
         id='img'>
  </div>

</template>
<script>
/*eslint-disable*/
export default {
  data () {
    return {
      context: '',
      context2: '',
      min: 100,
      max: 150,
      value: 100, //默认100%放大缩小
      naturalWidth: 0,
      naturalHeight: 0,
      width: 100,
      height: 300,
      percent: 100,
      imgUrl: '../../assets/woman.png'
      // imgUrl: require('../../assets/woman.png')
    };
  },
  mounted () {
    this.getImgWindthAndHeight().then(res => {
      console.log('res', res);
      const { naturalWidth, naturalHeight, img } = res;
      this.naturalWidth = naturalWidth
      this.naturalHeight = naturalHeight
      this.width = this.naturalWidth
      this.height = this.naturalHeight
      this.initCanvas()
      this.initCanvas2()
      console.log('img', img)
      this.context.drawImage(img, 0, 0, 237, 498)
      this.context.drawImage(this.context2, 0, 0)
    })
  },
  methods: {
    initCanvas () {
      var canvas = document.getElementById("canvas")
      this.context = canvas.getContext("2d")

    },
    initCanvas2 () {
      var canvas = document.getElementById("canvas2")
      this.context2 = canvas.getContext("2d")
      this.context2.fillStyle = "#FF0000";
      this.context2.fillRect(0, 0, 150, 75);
    },
    getImgWindthAndHeight () {
      return new Promise((resolve) => {
        var img = document.getElementById("img");
        img.onload = function () {
          resolve({
            naturalWidth: img.naturalWidth,
            naturalHeight: img.naturalHeight,
            img: img
          })
        }
      })
    },
  }
}
</script>

</style>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

没这种用法,这里 this.context2 应该传 canvas2

this.context.drawImage(this.context2, 0, 0)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...