我的代码就像这样
<html>
<head>
</head>
<body>
<canvas id="myCanvas" width="578" height="200" style="display:none;"></canvas>
<img id="canvasImg" onclick="myFunction()" alt="Right click to save me!">
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
function myFunction() {
var c = document.getElementsByTagName("canvas");
// save canvas image as data url (png format by default)
var dataURL = c.toDataURL();
// set canvasImg image src to dataURL
// so it can be saved as an image
document.getElementById('canvasImg').src = dataURL;
}
</script>
</body>
</html>
当我点击canvasImg
时抛出错误
Uncaught TypeError: Object #<NodeList> has no method 'toDataURL'
我做了fiddle here 任何人都可以指出什么是错的吗?
答案 0 :(得分:5)
document.getElementsByTagName
返回元素对象的数组,没有数组对象具有方法toDataUrl
而不是
var c = document.getElementsByTagName("canvas");
使用
var c = document.getElementsByTagName("canvas")[0];
答案 1 :(得分:2)
function myFunction() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var img = document.getElementById("canvasImg");
context.drawImage(img, 0, 0);
}