我有一段代码,用户必须按0才能使声音静音,或者1则播放音乐作品的声音。如果声音静音,则图像会改变,否则音乐播放时会发生变化。
var audio = new Audio();
window.onload = function geluidMaken() {
audio.src = "../Geluiden/Achtergrond_Geluid.mp3";
audio.play();
audio.loop = true;
window.addEventListener("keypress", function geluidsKnoppen() {
var codeGeluid = event.which || event.keyCode;
if(codeGeluid == 48) {
var geluidAanKnop = new Image();
geluidAanKnop.src = "../Afbeeldingen/Sound_Button.png";
mijnObject.drawImage(geluidAanKnop, (canvas.width/2)-25, 850, geluidAanKnop.width, geluidAanKnop.height);
audio.muted = true;
}
else if(codeGeluid = 49) {
var geluidAfKnop = new Image();
geluidAfKnop.src = "../Afbeeldingen/Mute_Button.png";
mijnObject.drawImage(geluidAfKnop, (canvas.width/2)-25, 850, geluidAfKnop.width, geluidAfKnop.height);
audio.muted = false;
}
});
}
我还有另一段代码,我将渲染所有其他函数
function tekenenObjecten() {
mijnObject.clearRect(0, 0, canvas.width, canvas.height);
makenBalkKort();
makenBal();
makenMuur();
makenBord();
图片在画布上不可见但是当我点击按键0或1时,图像会出现并直接消失。如何确保图像保留在画布上并在按下0或1时更改?
答案 0 :(得分:0)
在html5中使用画布时,请记住在重绘帧时,删除画布上的所有内容,然后在新帧中绘制要查看的所有内容。
在按键处理程序中,您可以绘制一次图像。当在代码的其他部分绘制新帧时,画布将被清除,并且您永远不会重绘它。
你想做的事情可能是一个总是被绘制的占位符,然后只改变它的来源并让主循环处理它。
var audioKnop = new Image();
var audioAanSource = "../Afbeeldingen/Sound_Button.png";
var audioMuteSource = "../Afbeeldingen/Mute_Button.png";
function init() {
audioKnop.src = audioMuteSource;
}
function tekenenObjecten() {
mijnObject.clearRect(0, 0, canvas.width, canvas.height);
makenBalkKort();
makenBal();
makenMuur();
makenBord();
maakAudioButton();
}
function maakAudioButton() {
mijnObject.drawImage(audioKnop, (canvas.width/2)-25, 850, audioKnop.width, audioKnop.height);
}
window.addEventListener("keypress", function () {
var codeGeluid = event.which || event.keyCode;
if(codeGeluid == 48) {
audioKnop.src = audioAanSource;
audio.muted = true;
} else if(codeGeluid == 49) {
audioKnop.src = audioMuteSource;
audio.muted = false;
}
});