vue canvas test

vue canvas test

by seo gyeongseok

HTML

<div id="app">
  <h2>Canvas Test</h2>
  <input
    ref="fileInput"
    type="file"
    accept="image/*"
    @change="onChangeFileInput"
  />
  <canvas ref="myCanvas" class="myCanvas"></canvas>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #ffffff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

.myCanvas {
  width: 400px;
  height: 300px;
  border: 1px solid #20262E;
}

Vue

new Vue({
  el: "#app",
  data: {},
  methods: {
    getImageResolution (result) {
      return new Promise((resolve) => {
        const image = new Image()
        image.src = result

        image.onload = () => {
          const { width, height } = image

          resolve({
            width,
            height
          })
        }
      })
    },
    readImageFile (file) {
      const fileReader = new FileReader()
      fileReader.onprogress = (evt) => {
        if (evt.lengthComputable) {
          const { loaded, total } = evt
          console.log(`File load progress > ${loaded}/${total}`)
        }
      }

      fileReader.onerror = (evt) => {
        const { error } = evt.target
        this.fireOnChangeImage(error)
      }

      fileReader.onload = (evt) => {
        const { result } = evt.target

        this.getImageResolution(result)
          .then((size) => {
            if (this.validImageResolution(size)) {
              this.imageFile = file
              this.imageFileThumbnail = result
            } else {
              const { validWidth, validHeight } = this
              const message = `Sorry, We allow image resolution (${validWidth} x ${validHeight})`
              return new Error(message)
            }
          })
          .then((error) => {
            this.fireOnChangeImage(error)
          })
      }

      // read file data
      fileReader.readAsDataURL(file)
    },
    onChangeFileInput () {
      const file = this.$refs.fileInput.files[0]

      if (file) {
        this.readImageFile(file)
      }
    }
  }
})