html 使用canvas和vuejs将URL从url转换为base64
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html 使用canvas和vuejs将URL从url转换为base64相关的知识,希望对你有一定的参考价值。
'use strict';
var vue = new Vue({
el: '#app',
data: {
url: '',
base64: '',
error: ''
},
methods: {
generateBase64: function generateBase64() {
var _this = this;
var canvas = document.createElement('CANVAS');
var img = document.createElement('img');
img.src = this.url;
img.onload = function () {
canvas.height = img.height;
canvas.width = img.width;
_this.base64 = canvas.toDataURL('image/png');
canvas = null;
};
img.onerror = function (error) {
_this.error = 'Could not load image, please check that the file is accessible and an image!';
};
}
},
watch: {
url: function url() {
this.base64 = '';
this.error = '';
}
}
});
Vue.config.devtools = false;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</head>
<body>
<div id="app">
<input v-model="url">
<button :disabled="!url.length" @click="generateBase64">Generate base64</button>
<hr>
<div v-show="base64">
Your image as base64:
<code>
{{ base64 }}
</code>
</div>
<div v-show="error">
{{ error }}
</div>
</div>
<script id="jsbin-javascript">
'use strict';
var vue = new Vue({
el: '#app',
data: {
url: '',
base64: '',
error: ''
},
methods: {
generateBase64: function generateBase64() {
var _this = this;
var canvas = document.createElement('CANVAS');
var img = document.createElement('img');
img.src = this.url;
img.onload = function () {
canvas.height = img.height;
canvas.width = img.width;
_this.base64 = canvas.toDataURL('image/png');
canvas = null;
};
img.onerror = function (error) {
_this.error = 'Could not load image, please check that the file is accessible and an image!';
};
}
},
watch: {
url: function url() {
this.base64 = '';
this.error = '';
}
}
});
Vue.config.devtools = false;
</script>
<script id="jsbin-source-javascript" type="text/javascript">let vue = new Vue({
el: '#app',
data: {
url: '',
base64: '',
error: ''
},
methods: {
generateBase64 () {
let canvas = document.createElement('CANVAS')
let img = document.createElement('img')
img.src = this.url
img.onload = () => {
canvas.height = img.height
canvas.width = img.width
this.base64 = canvas.toDataURL('image/png')
canvas = null
}
img.onerror = error => {
this.error = 'Could not load image, please check that the file is accessible and an image!'
}
}
},
watch: {
url () {
this.base64 = ''
this.error = ''
}
}
})
Vue.config.devtools = false</script></body>
</html>
以上是关于html 使用canvas和vuejs将URL从url转换为base64的主要内容,如果未能解决你的问题,请参考以下文章
VueJS开发所用到的技术栈
使用html2Canvas生成图片跨域如何处理?
使用 vuejs 和 laravel 在 URL 中传递参数
VUEJS-如何从 url 中删除参数
无法从 AngularJS index.html 导航到 VueJS webapp
如何将图像从 url 沿侧输入类型文件加载到 html5 画布?