期望的行为是当文档加载时,canvas 绘制图像 0。当单击不可见的 div 时,canvas 绘制图像 1,在 mouseup 或 mouseout 上,它恢复为图像 0。
我将 css 排除在外,因为我可以正常工作...只需要知道我在 javascript 函数上做错了什么。现在它不显示任何内容,甚至第一张图片也不显示。
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function imgChange(imagePath)
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
};
img.src=imagePath; <!-- I THINK THIS IS WRONG?
</script>
</head>
<body>
<canvas id="myCanvas" width="506" height="319"
onload="imgChange('0.gif')" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<div id="button1" onMouseDown="imgChange('1.gif')" onMouseUp="imgChange('0.gif')" onMouseOut="imgChange('0.gif')"></div>
<div id="key2"></div>
</body>
</html>
最佳答案
您的代码缺少结束 block
function imgChange(imagePath) {
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
};
img.src=imagePath;
}
最后一个'}'不见了
关于javascript - 使用javascript更改 Canvas 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10763229/