Skip to content

Instantly share code, notes, and snippets.

@galvez
Created April 2, 2019 15:29
Show Gist options
  • Save galvez/d5d4ae6da2fd5de41cfe4f3f4f3de31d to your computer and use it in GitHub Desktop.
Save galvez/d5d4ae6da2fd5de41cfe4f3f4f3de31d to your computer and use it in GitHub Desktop.
<template>
<img ref="img" />
</template>
<script>
export default {
props: ['src'],
data: () => ({ blob: null }),
beforeMount () {
this.$watch('src', this.loadImage)
},
async mounted () {
if (this.src) {
await this.loadImage(this.src)
}
},
methods: {
loadImage (src) {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
const img = this.$refs.img
return new Promise((resolve) => {
img.onload = () => {
canvas.width = img.naturalWidth
canvas.height = img.naturalHeight
ctx.drawImage(img, 0, 0)
canvas.toBlob((blob) => {
this.blob = blob
resolve()
}, 'image/jpeg', 1.0)
}
img.src = src
img.crossOrigin = ''
})
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment