我一直试图让画布在点击时来回改变颜色,但它只是从红色变为绿色而不是再次回来,我尝试了一段时间循环但这似乎不起作用
<canvas onclick="colorchangefunction()" id="testCanvas" width="320" height="240"
style="border: 1px solid black;">
</canvas>
<script>
function colorchangefunction(){
window.alert("colorchangefunction started")
if (color = "r"){
context.fillStyle = "green";
context.fillRect(20,20,150,75)
var color = "g"
}
else if (color = "g") {
context.fillStyle = "red";
context.fillRect(20,20,150,75)
var color = "r"
}
window.alert("colorchangefunction ended")
}
var canvas =document.getElementById("testCanvas");
var context = canvas.getContext("2d");
context.fillStyle = "red";
context.fillRect(20,20,150,75)
var color = "r"
</script>
有什么想法吗?
答案 0 :(得分:0)
不在if语句中创建新变量应该为您解决。而不是var color =
只需color =
。