我正在尝试创建一个javascript幻灯片,这是我当前的代码:
window.onload = function() {
var c = document.getElementById("frame");
var ctx = c.getContext("2d");
var img = document.getElementById("s1");
ctx.drawImage(img, 0, 0, 300, 190);
}
function scene2() {
var img1 = document.getElementById("s2");
ctx.drawImage(img1, 0, 0, 300, 190);
};
.i {
display: none;
}
canvas {
border: 5px solid #000000;
width: 910;
height: 500;
}
<img class="i" id="s1" src="Images/scene1.png"></img>
<img class="i" id="s2" src="Images/scene2.png"></img>
<canvas id="frame"></canvas>
<button onclick="scene2()">A</button>
但是,当我按下a按钮转到下一张幻灯片时,它会停留在第一张幻灯片上。我怎样才能解决这个问题?提前谢谢。
答案 0 :(得分:0)
函数scene2为变量创建新范围,ctx变量在那里不可见。看看这段代码:
<html>
<img class="i" id="s1" src="http://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded&a"></img>
<img class="i" id="s2" src="http://hammerjs.github.io/assets/img/stackoverflow-icon.svg"></img>
<canvas id="frame"></canvas>
<button onclick="scene2()">A</button>
<script>
window.onload = function() {
var c=document.getElementById("frame");
var ctx=c.getContext("2d");
var img=document.getElementById("s1");
ctx.drawImage(img,0,0,300,190);
}
function scene2(){
var c=document.getElementById("frame");
var ctx=c.getContext("2d");
var img1=document.getElementById("s2");
ctx.drawImage(img1,0,0,300,190);
};
</script>
<style>
.i{
display: none;
}
canvas{
border: 5px solid #000000;
width:910;
height:500;
}
</style>
</html>