I upload a picture from the computer, and then I want to push it up by pressing a button, why does JS say that the picture is not defined?

function draw() { //upload var ctx = document.getElementById('canvas').getContext('2d'), img = new Image(), f = document.getElementById("uploadimage").files[0], url = window.zURL || window.URL, src = url.createObjectURL(f); img.src = src; img.onload = function() { //ctx.drawImage(img, 0, 0); // ctx.drawImage(img, 0, 0, canvas.width, canvas.height) ; ctx.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,(img.height*canvas.width)/img.width);//вписываниС Π² ΡˆΠΈΡ€ΠΈΠ½Ρƒ } } document.getElementById("uploadimage").addEventListener("change", draw, false) function qwe() { var ctx = document.getElementById('canvas').getContext('2d'); ctx.drawImage(img,0,0,img.width,img.height,0,-500,canvas.width,(img.height*canvas.width)/img.width);//вписываниС Π² ΡˆΠΈΡ€ΠΈΠ½Ρƒ } 
 <button onclick="qwe()">Move </button> <input type="file" name="img" id="uploadimage" size="1" class="input_input_style"> <canvas id="canvas" width="1200" height="1000"></canvas> 

    1 answer 1

    You have no img variable in the qwe() function

     var img; function draw() { //upload var ctx = document.getElementById('canvas').getContext('2d'); img = new Image(); var f = document.getElementById("uploadimage").files[0], url = window.zURL || window.URL, src = url.createObjectURL(f); img.src = src; img.onload = function() { //ctx.drawImage(img, 0, 0); // ctx.drawImage(img, 0, 0, canvas.width, canvas.height) ; ctx.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,(img.height*canvas.width)/img.width);//вписываниС Π² ΡˆΠΈΡ€ΠΈΠ½Ρƒ }; }; document.getElementById("uploadimage").addEventListener("change", draw, false) function qwe() { var ctx = document.getElementById('canvas').getContext('2d'); ctx.drawImage(img,0,0,img.width,img.height,0,-500,canvas.width,(img.height*canvas.width)/img.width);//вписываниС Π² ΡˆΠΈΡ€ΠΈΠ½Ρƒ } 
     <button onclick="qwe()">Move </button> <input type="file" name="img" id="uploadimage" size="1" class="input_input_style"> <canvas id="canvas" width="1200" height="1000"></canvas>