[英]adding images to a html5 canvas
I'm trying to add an image to my canvas but it doesn't seem to work I've taken a look and can't see anything wrong with my code but maybe someone else can. 我正在尝试将图像添加到画布上,但似乎无法正常工作,我已经看过了,看不到我的代码有任何问题,但也许有人可以。
This is my JS file. 这是我的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();
Here's my HTML mabye this will help find the problem 这是我的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>
the problem is, that you declare canvas & context in onLoad() but try to access it in draw(). 问题是,您在onLoad()中声明canvas&context,但是尝试在draw()中访问它。
so, by making them global, the problem is solved: 因此,通过使其具有全局性,可以解决问题:
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';
}
Try to draw image on it's onload event 尝试在onload事件上绘制图像
sun.onload = function() {
context.drawImage(sun, 100, 100);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.