我最近开始学习HTML,我试图从一个数组生成随机图像(我目前只有2个图像)。我得到的错误是:
Blockquote Uncaught ReferenceError:未定义randomImg 在HTMLButtonElement.onclick(tryit.asp?filename = tryhtml5_canvas_tut_img:1) onclick @ tryit.asp?filename = tryhtml5_canvas_tut_img:1
我的代码是:
<!DOCTYPE html>
<html>
<body>
<img id="scream" src="https://cdn.modernfarmer.com/wp-
content/uploads/2014/09/cowhero2.jpg" alt="cow1" width="1200" height="742">
<p>Canvas to fill:</p>
<canvas id="myCanvas" width="1300" height="800"
style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<p><button onclick="randomImg()">Generate an error</button></p>
<script language="JavaScript" type="text/javascript">
function randomImg() {
var randomNumber = Math.floor(Math.random() * 2);
var imgName = cow[randomNumber];
console.log(imgName);
console.log("myCanvas was run")
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img =r document.getElementById("imageid").src= https: + "//" +
imgur.com + "/" + imgName;
ctx.drawImage(img,10,10);
}
</script>
</body>
</html>
还应该注意的是,我只是w3schools html shell。
答案 0 :(得分:0)
这可以通过展示示例来帮助您。我知道随机40应该可以正常工作。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="640" height="640"></canvas>
<script>
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
var imname = getRandomInt(40);
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
};
imageObj.src = 'https://jacknorthrup.com/junk/'+imname+'.jpg';
</script>
</body>
</html>