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;
margin-top: 10px;
border: 1px solid #20262E;
}
Vue
new Vue({
el: "#app",
data: {},
methods: {
drawImageToCanvas (image) {
const canvas = this.$refs.myCanvas
const ctx = canvas.getContext('2d')
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(image, 0, 0, image.width, image.height,
0, 0, canvas.width, canvas.height)
},
getImage (result) {
return new Promise((resolve) => {
const image = new Image()
image.src = result
image.onload = () => {
resolve(image)
}
})
},
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.getImage(result)
.then((image) => {
const { width, height } = image
console.log(`upload image (${width} * ${height})`)
this.drawImageToCanvas(image)
})
}
// read file data
fileReader.readAsDataURL(file)
},
onChangeFileInput () {
const file = this.$refs.fileInput.files[0]
if (file) {
this.readImageFile(file)
}
}
}
})