对于家庭作业,我想制作一个互动的故事。 基本上,它只使用向上和向下按钮点击图像。 但我的问题是: 我的If函数结束在
之前写入if函数它应该像点击图库一样工作,非常简单,但我找不到解决方案...... `
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var startImg = new Image();
startImg.onload = update;
startImg.src = 'img/start.png';
var eins = new Image();
eins.onload = update;
eins.src = 'img/1.png';
var zwei = new Image();
zwei.onload = update;
zwei.src = 'img/2.png';
window.onkeydown = function(e) {
e.preventDefault();
console.log(e.keyCode);
if(e.keyCode == 38) {
weiter('UP');
}
else if(e.keyCode == 39) {
weiter('RIGHT');
}
else if(e.keyCode == 40) {
weiter('DOWN');
}
else if(e.keyCode == 37) {
weiter('LEFT');
}
}
function update() {
ctx.clearRect(0,0, 500,500);
ctx.drawImage(startImg, 0, 0, 500, 500);
}
function weiter(dir){
if(dir == 'UP') {
ctx.clearRect(0,0, 500,500);
ctx.drawImage(eins, 0, 0, 500, 500);
}
context.closePath();
context.fill();
if(dir == 'UP') {
ctx.clearRect(0,0, 500,500);
ctx.drawImage(zwei, 0, 0, 500, 500);
}
context.closePath();
context.fill();
}
</script>
`
答案 0 :(得分:0)
你对自己的想法很满意,有些事情会导致你的问题。当你有IF语句时,你需要程序在找到命中时停止。这就是你使用keylistener功能所用的地方。
也不需要在图像上关闭路径(),也不需要填充它。
这是我为你做的一个小提琴:http://jsfiddle.net/Niddro/u7qttjcn/
我添加了几条评论来解释我的所作所为。我希望你能遵循逻辑。我也选择了自己的图片=)
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var currentImage = 0; //start at starting image as default
//Creating image library
var images = new Array();
images[0] = new Image(); //start image
images[0].src = 'http://minimotives.com/wp-content/uploads/2014/09/Start_button_large.png';
images[1] = new Image(); //image 1
images[1].src = 'http://one_org_international.s3.amazonaws.com/international/wp-content/uploads/2013/08/one-logo-og-image.jpg';
images[2] = new Image(); //image 2
images[2].src = 'http://images.clipartpanda.com/number-2-clipart-11478-blue-number-two-clip-art.png';
window.onkeydown = function(e) {
e.preventDefault();
console.log(e.keyCode);
if(e.keyCode == 38) { //arrow up
currentImage++; //go to next page
}
else if(e.keyCode == 40) { //arrow down
currentImage--; //go one page back
}
else if(e.keyCode == 39) { //arrow right
//do nothing
}
else if(e.keyCode == 37) { //arrow left
//do nothing
}
//Now we need to check to see if we are above or under the number of pages
if (currentImage > images.length-1) {
currentImage = images.length-1;
}
else if (currentImage < 0) {
currentImage = 0;
}
update(); //update the canvas after each keypress
}
//clear the canvas and draw image from library
function update() {
ctx.clearRect(0,0, canvas.width,canvas.height);
ctx.drawImage(images[currentImage], 0, 0);
}
//At the end of everything, we need to call the update function to show the start image.
update();
<canvas id="canvas" widht="600" height="600"></canvas>