我正在尝试将图像添加到我的画布中,但它似乎无法正常工作我已经看了一眼,看不出我的代码有什么问题,但也许其他人可以。
这是我的JS档案。
if (window.addEventListener)
{
window.addEventListener( 'load', onLoad, false);
}
function onLoad()
{
var canvas;
var context;
function initialise()
{
canvas = document.getElementById('canvas');
if (!canvas.getContext)
{
alert('Error: no canvas.getContext!');
return;
}
context = canvas.getContext('2d');
if (!context)
{
alert('Error: failed to getContext!');
return;
}
}
}
function draw()
{
var sun = new Image();
sun.src = 'images.sun.png';
context.drawImage(sun, 100, 100);
}
onLoad();
draw();
这是我的HTML mabye,这将有助于找到问题
<!doctype html>
<html>
<head>
<title>Test</title> <script type="text/javascript" src="javascript/canvas.js"></script>
</head>
<body>
<canvas id="canvas" width="800" height="600">
Your browser does not support the canvas tag
</canvas>
</body>
</html>
答案 0 :(得分:1)
问题是,你宣布画布&amp; onLoad()中的上下文,但尝试在draw()中访问它。
所以,通过使它们成为全局,问题就解决了:
var canvas;
var context;
if (window.addEventListener) {
window.addEventListener('load', function(){
onLoad();
}, false);
}
function onLoad() {
initialise();
draw();
}
function initialise() {
canvas = document.getElementById('canvas');
if (!canvas.getContext) {
alert('Error: no canvas.getContext!');
return;
}
context = canvas.getContext('2d');
if (!context) {
alert('Error: failed to getContext!');
return;
}
}
function draw() {
var sun = new Image();
sun.addEventListener('load', function(){
context.drawImage(sun, 100, 100);
}, false);
sun.src = 'http://puu.sh/1yKaY';
}
答案 1 :(得分:0)
尝试在onload事件上绘制图像
sun.onload = function() {
context.drawImage(sun, 100, 100);
};