举个例子是这样的,下面的代码是可以的:
<p hidden>
<canvas id="test"></canvas>
</p>
<p id="img"></p>
<script type="text/javascript">
window.onload = function(){
var canvas = document.getElementById("test");
canvas.width = 800;
canvas.height = 600;
var context = canvas.getContext("2d");
context.fillStyle = "#FFF";
context.fillRect(0,0,800,600);
var img = new Image();
img.src = "./qrcode.jpeg";
img.onload = function(){
context.drawImage(img,200,50);
var image = canvas.toDataURL("image/jpeg",0.5);
$("#img").append('<img src="'+image+'" />');
}
};
</script>
但是把canvas绘制部分一封装就出错:
<p hidden>
<canvas id="test"></canvas>
</p>
<p id="img"></p>
<script type="text/javascript">
window.onload = function(){
$("#img").append('<img src="'+canvasDraw()+'" />');
};
function canvasDraw(){
var canvas = document.getElementById("test");
canvas.width = 800;
canvas.height = 600;
var context = canvas.getContext("2d");
context.fillStyle = "#FFF";
context.fillRect(0,0,800,600);
var img = new Image();
img.src = "./qrcode.jpeg";
img.onload = function(){
context.drawImage(img,200,50);
var image = canvas.toDataURL("image/jpeg",0.5);
return image;
}
}
</script>
控制台就出现 GET http://localhost/undefine 404
错误,然后显示不出来
所以这样的原因是什么?
巴扎黑2017-04-11 12:12:57
你这样封装不对呀;
window.onload = function(){
$("#img").append('<img src="'+canvasDraw()+'" />');
};
你这么写,canvasDraw
这个方法应该是return图片的src地址的。
但是看你的方法实现,你放到onload里面return了,也就是说canvasDraw
没有return吧,所以调用这个方法的时候 ,返回了undefined,
所以控制台才说GET http://localhost/undefine 404
.