canvas将图片转为base64

时间:2023-12-19 12:25:20

最简例子

<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title>canvas将图片转为base64</title>
<style type="text/css">
body {
margin: 0;
}
</style>
</head> <body>
<img src="//img.alicdn.com/tps/i2/TB1bNE7LFXXXXaOXFXXwFSA1XXX-292-116.png" id="img" />
<canvas id="load_area" width="100%" height="224px"></canvas>
<script type="text/javascript">
var imgEl = document.getElementById('img');
var loadCanvas = document.getElementById('load_area');
var context = loadCanvas.getContext('2d');
var base64Str = '';
var tmpImage = new Image();
tmpImage.setAttribute('crossOrigin', 'anonymous');
tmpImage.src = imgEl.src;
tmpImage.onload = function() {
loadCanvas.width = imgEl.width;
loadCanvas.height = imgEl.height;
context.drawImage(tmpImage, 10, 10);
base64Str = loadCanvas.toDataURL('image/jpg');
};
</script>
</body> </html>

纯js版

var appendCanvas = function() {
var body = document.body;
var canvas = document.createElement('canvas');
body.appendChild(canvas);
return canvas;
}; var createImage = function(url) {
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
return img;
}; var imageToBase64 = function(url) {
var canvas = appendCanvas();
var context = canvas.getContext('2d');
var tmpImage = createImage(url);
var base64Str = '';
tmpImage.onload = function() {
canvas.width = tmpImage.width;
canvas.height = tmpImage.height;
context.drawImage(tmpImage, 0, 0);
base64Str = canvas.toDataURL('image/jpg');
console.log(base64Str);
};
};