要使用图像数据URL加载画布,我们可以进行AJAX调用以获取数据URL,使用URL创建图像对象,然后使用画布上下文的drawImage()方法将图像绘制到画布上。
html代码:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
function loadCanvas(dataURL) {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// load image from data url
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(this, 0, 0);
};
imageObj.src = dataURL;
}
// make ajax call to get image data url
var request = new XMLHttpRequest();
request.open('GET', 'https://www.html5canvastutorials.com/demos/assets/dataURL.txt', true);
request.onreadystatechange = function() {
// Makes sure the document is ready to parse.
if(request.readyState == 4) {
// Makes sure it's found the file.
if(request.status == 200) {
loadCanvas(request.responseText);
}
}
};
request.send(null);
</script>
</body>
</html>