HTML5中drawImage用法分析
本文实例分析了HTML5中drawImage使用时遇到的问题及解决方法。分享给大家供大家参考。具体分析如下:
使用Image遇到的问题:
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/jquery-1.9.1.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function() {
var jsCanv = document.getElementById("canv");
var oCanv = jsCanv.getContext("2d");
var img = new Image();
img.src = "img.png";
oCanv.drawImage(img, 220, 30);
})
</script>
</head></p> <p> <body>
<canvas id="canv" width="500" height="500">
浏览器不支持
</canvas>
</body>
</html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/jquery-1.9.1.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function() {
var jsCanv = document.getElementById("canv");
var oCanv = jsCanv.getContext("2d");
var img = new Image();
img.src = "img.png";
oCanv.drawImage(img, 220, 30);
})
</script>
</head></p> <p> <body>
<canvas id="canv" width="500" height="500">
浏览器不支持
</canvas>
</body>
</html>
其实这种写法是有错误的,实际上只要一刷新图片就不显示出来。要想保证刷新正常显示需要在Image onload的时候重绘一次才行。测试在chrome 19下会出现的问题。
解决方案
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/jquery-1.9.1.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function() {
var jsCanv = document.getElementById("canv");
var oCanv = jsCanv.getContext("2d");
var img = new Image();
img.src = "img.png";
img.onload = function() {
oCanv.drawImage(img, 220, 30);
}
})
</script>
</head>
<body>
<canvas id="canv" width="500" height="500">
浏览器不支持
</canvas>
</body>
</html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/jquery-1.9.1.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function() {
var jsCanv = document.getElementById("canv");
var oCanv = jsCanv.getContext("2d");
var img = new Image();
img.src = "img.png";
img.onload = function() {
oCanv.drawImage(img, 220, 30);
}
})
</script>
</head>
<body>
<canvas id="canv" width="500" height="500">
浏览器不支持
</canvas>
</body>
</html>
本文网址:https://www.dedexuexi.com/wysj/html5/2827.html
本站部分文章搜集与网络,如有侵权请联系本站,转载请说明出处。
标签:前端