使用 javascript 更改画布图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10763229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
change canvas image with javascript
提问by 3z33etm
the desired behavior is when the document loads, canvas draws image 0. when the invisible div is clicked, canvas draws image 1, on mouseup or mouseout, it reverts back to image 0.
所需的行为是当文档加载时,canvas 绘制图像 0。当单击不可见的 div 时,canvas 绘制图像 1,在 mouseup 或 mouseout 时,它恢复为图像 0。
I left the css out because I got that working...just need to know what I'm doing wrong with the javascript function. right now it doesn't display anything, not even the first image.
我离开了 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>
回答by AlanFoster
your code is missing an ending 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;
}
The last '}' is missing
缺少最后一个“}”
回答by Mohsen
JavaScript looks good. But you can't clickon an invisible div
. Make the div visible and try.
JavaScript 看起来不错。但是你不能点击一个不可见的div
. 使 div 可见并尝试。
Be aware of same origin policy too. Image path should be in your domain. If you are running in localhost you might need to have a local HTTP server.
也要注意同源政策。图片路径应该在您的域中。如果您在 localhost 中运行,您可能需要有一个本地 HTTP 服务器。