说到画布,我是全新的。我正在尝试在画布上绘制图像,然后对其进行动画处理。现在我无法在屏幕上绘制图像。图像根本不显示。
这里是部分代码:
var car = new Image();
car.src = "http://i.imgur.com/8jV4DEn.png";
car.x = 40; car.y = 60;
function draw(){
ctx.drawImage(car.src, car.x, car.y);
}
谢谢!
说到画布,我是全新的。我正在尝试在画布上绘制图像,然后对其进行动画处理。现在我无法在屏幕上绘制图像。图像根本不显示。
这里是部分代码:
var car = new Image();
car.src = "http://i.imgur.com/8jV4DEn.png";
car.x = 40; car.y = 60;
function draw(){
ctx.drawImage(car.src, car.x, car.y);
}
谢谢!
代码有几个问题。
onload
处理程序x
和y
属性 - 这些是只读属性draw
而不是animate
reqAnimFrame
poly 不承认 non- requestAnimationFrame
prefixed 。这是调整后的代码和修改后的小提琴:
var reqAnimFrame =
window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
c.height = window.innerHeight;
c.width = window.innerWidth;
var car = new Image();
/// when image is loaded, call this:
car.onload = animate;
/// x and y cannot be used, in "worse" case use this but ideally
/// use a custom object to set x and y, store image in etc.
car._x = 40;
car._y = 60;
car.src = "http://i.imgur.com/8jV4DEn.png";
var speed = 5;
function animate(){
car._y += speed;
draw();
reqAnimFrame(animate);
}
function draw(){
/// clear background
ctx.clearRect(0, 0, c.width, c.height);
/// cannot draw a string, draw the image:
ctx.drawImage(car, car._x, car._y);
}
/// don't start animate() here
//animate();