Uncaught DOMException: Failed to execute 'drawImage' on 'CanvasRenderingContext2D':
canvas学习报错问题
·
问题:Uncaught DOMException: Failed to execute 'drawImage' on 'CanvasRenderingContext2D':The HTMLImageElement provided is in the 'broken' state.
分析:Uncaught DOMException表明未获取dom元素
The HTMLImageElement provided is in the 'broken' state.表明元素在获取过程中被中断了,也即元素可能没有正确获取
图片路径不正确导致图片未正确获取也将导致该错误
代码
HTML文件
<!DOCTYPE>
<html>
<head>
<mata name="viewport" content="width=device-width,initial-scale=1">
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
</head>
<body>
<div>
<canvas id="start" width="800" height="600">
</canvas>
</div>
<img src="./img/girl.jpg" id="img" style="display:none"/> <!--正确路径-->
<script type="text/javascript" src="js/commonFunctions.js"></script>
<script type="text/javascript" src="js/star.js"></script>
</body>
</html>
start.js:
var can;
var ctx;
var width;
var height;
var imgGirl=new Image();
// $(document).ready(function(){
// init();
// })
document.body.οnlοad=init;
function init(){
can=document.getElementById("start");
ctx=can.getContext("2d");
width=can.width;
height=can.height;
imgGirl.src="../img/girl.jpg"//注意文件路径 正确路径为:./img/girl.jpg
gameLoop();
}
function drawBg(){
ctx.fillStyle="#393550";
ctx.fillRect(0,0,width,height);
}
/** [gameLoop 刷新画布] */
function gameLoop(){
window.requestAnimFrame(gameLoop);
drawBg();
drawImg();
}
//根据设备性能进行调用
function drawImg(){
// star.js:39 Uncaught DOMException: Failed to execute 'drawImage' on 'CanvasRenderingContext2D':
// The HTMLImageElement provided is in the 'broken' state.
// 分析:Uncaught DOMException表明未获取dom元素
// The HTMLImageElement provided is in the 'broken' state.表明元素在获取过程中被中断了,也即元素可能还在加载中
ctx.drawImage(imgGirl,100,100)
}
解决办法:
先判断图片路径在js中是否正确:
在html中添加img标签,通过js赋值看是否可以正常显示,若可以则路径正确
更多推荐
所有评论(0)