1
我需要將圖像上載到畫布上,但圖像一直在畫布旁邊而不是在畫布內。我爲此做了一個代碼,但不起作用。提前致謝。將圖像放到畫布上
JS:
//Link Canvas
var canvas = document.getElementById('gameCanvas');
var context = canvas.getContext('2d');
var width = $('#gameCanvas').width();
var height = $('#gameCanvas').height();
//Car Image
var car = new Image();
car.src = "http://images.clipartpanda.com/car-top-view-clipart-red-racing-car-top-view-fe3a.png";
//Car x,y Position
var x = 220;
var y = 200;
//Car Speed and angle
var speed = 7;
var angle = 0;
var mod = 0;
//Keyboard Listeners
window.addEventListener("keydown", keypress_handler, false);
window.addEventListener("keyup", keyup_handler, false);
var moveInterval = setInterval(function() {
draw();
}, 30);
//Draw Car
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
//Rotate Car When Turning
x += (speed * mod) * Math.cos(Math.PI/180 * angle);
y += (speed * mod) * Math.sin(Math.PI/180 * angle);
context.save();
context.translate(x, y);
context.rotate(Math.PI/180 * angle);
context.drawImage(car, -(car.width/2), -(car.height/2));
context.restore();
}
//Keyboard Function
function keyup_handler(event) {
console.log('a');
if (event.keyCode == 38 || event.keyCode == 40) {
mod = 0;
}
}
//Keyboard keys to operate car
function keypress_handler(event) {
console.log(event.keyCode);
if (event.keyCode == 38) { //Up arrow
mod = 1;
}
if (event.keyCode == 40) { //Down arrow
mod = -1;
}
if (event.keyCode == 37) { //Left Arrow
angle -= 5;
}
if (event.keyCode == 39) { //Right Arrow
angle += 5;
}
}
function update() {
window.requestAnimationFrame(update);
x += speed;
y += speed;
if (x >= $('#gameCanvas')){
speed = 0;
}
if (y >= $('#gameCanvas')){
speed = -1.0 * speed;
speed = 0;
}
}
代碼不起作用:使用此代碼
var URL = [
"http://thumb101.shutterstock.com/display_pic_with_logo/69386/69386,1162932792,3/stock-photo-lone-car-in-four-lanes-from-above-2128171.jpg",
];
var canvas
var imgs = URL.map(function(URL) {
var img = new Image();
img.src = URL;
document.body.appendChild(img);
return img;
});
IM,拍攝的圖像到畫布上,但然後就離開。 – 2014-11-04 02:19:35