Currently working on a JavaScript project to create a captcha display on a canvas. The issue I'm facing is that the background image does not load when the page initially opens. However, upon hitting the refresh button, it functions as intended. Here's the code snippet:
<script>
var code = {};
function canvas(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
var background = new Image();
background.src = "http://gazell.io/wp-content/uploads/2016/10/image011.png";
ctx.drawImage(background, 0 ,0);
var list = new Array('@','%','#','$','*','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9');
var i;
for (i=0;i<6;i++){
var a = list[Math.floor(Math.random() * list.length)];
var b = list[Math.floor(Math.random() * list.length)];
var c = list[Math.floor(Math.random() * list.length)];
var d = list[Math.floor(Math.random() * list.length)];
var e = list[Math.floor(Math.random() * list.length)];
var f = list[Math.floor(Math.random() * list.length)];
var g = list[Math.floor(Math.random() * list.length)];
}
code.value = a + b + c + d + e + f + g;
ctx.font = "italic 42px verdana";
ctx.fillStyle="#FF9912";
ctx.textAlign = "center";
ctx.fillText(code.value, canvas.width/2,canvas.height/2);
}
window.onload = canvas();
function ValidCaptcha(){
//var string1 = document.getElementById('canvas').value;
var string1 = document.getElementById('text').value;
var string2 = code.value;
if(string1 != null){
if(string1 == string2){
alert("true");
}else{
alert("false");
}
}
}
</script>
Seeking assistance on displaying the canvas background immediately upon page load rather than relying on the refresh button.
<body onload="canvas();">
<div class="box">
<h1>Testing Captcha</h1>
<canvas id="canvas" height="80" width="260"></canvas>
<input id="text" type="text"></input>
<button id="btn" onclick="canvas();">Refresh</button>
<button type="button" value="Check" onclick="ValidCaptcha();">Submit</button>
</div>
</body>