canvas画像をbase 64に変換
4320 ワード
<html>
<head>
<meta charset="UTF-8">
<title>canvas base64title>
head>
<body>
<p>canvas p>
<canvas id="canvas">canvas>
<p>img base64 p>
<img src="" id="img">
<script>
// https://www.jianshu.com/p/6fe06667b748
//
var image = "https://www.xx.jpg"
//
convertImageToBase64(image)
function convertImageToBase64(image) {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
var imgObj = new Image();
//
imgObj.setAttribute("crossOrigin",'anonymous')
// image src ,
imgObj.src = image;
// , canvas
imgObj.onload = function () {
// canvas
canvas.width = this.width;
canvas.height = this.height;
ctx.drawImage(this, 0, 0);
// base64
var img = canvas.toDataURL("image/jpeg", 0.5); // toDataUrl 2 , : , : 0-1( 0.92)
document.getElementById('img').setAttribute("src", img) // base64
}
}
script>
body>
html>