<div style="position:absolute; left:625px; top:100px; background-color:white;">
<button id="btn1" type="button" onclick="detain()">Detain</button>
<button id="btn2" type="button" onclick="free()">Free them</button>
</div>
<img id="Man1" width="0" height="0" src="Man1.PNG" alt="Man1">
<img id="Man2" width="0" height="0" src="Man2.PNG" alt="Man2">
<canvas id="myCanvas" width="600" height="450" style="border:1px solid grey;"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
changeImage("Man2"); //First image loaded on the canvas
function detain() {
alert('The guy was disappointed. The guards come in and detain him. I think I made the wrong choice');
document.getElementById('btn2').disabled = false;
document.getElementById('btn1').disabled = true;
changeImage("Man1"); //Change based on button click
}
function free() {
alert('The guy sighs in relief and looks happy. The guards guide him to the exit. I think I made the right decision');
document.getElementById('btn1').disabled = false;
document.getElementById('btn2').disabled = true;
changeImage("Man2"); //Change based on button click
}
function changeImage(imageId) {
var img = document.getElementById(imageId);
ctx.clearRect(0, 0, canvas.width, canvas.height); //This should clear the canvas
ctx.drawImage(img, 10, 10);
}
</script>
在此代码片段中,按钮单击是在脚本标记内部处理的,特别是在创建画布并且存在引用之后。 由于我还没有对此进行测试,请提供反馈,我最终会编辑需要的内容。