How can I make it so that the picture is loaded into canvas either from the manually specified url or from the drop-down list? html code snippet:

<select id="image-select"> <option value=""></option> <option value="http://www.captionite.com/templates/good_guy_greg.jpg">Good guy Greg</option> <option value="http://www.captionite.com/templates/scumbag_steve.jpg">Scumbag Steve</option> <option value="http://www.captionite.com/templates/high_expectations_asian_father.jpg">High Expectations Asian Father</option> </select> 

js began to study more recently and much is still not clear. Here is the raw js code snippet:

 var canvas = document.getElementById("myCanvas"); var context = document.getContext("2d"); var getImage = function(){ var selectList = document.getElementById("image-select"); var source = selectList.options[selectList.selectedIndex].value; var img = new Image (); img.src = source; }; img.onload = function() { // Work out where to center it x = canvas.width/2 - img.width/2; y = canvas.height/2 - img.height/2; // Draw it context.drawImage(img, x, y); }; getImage(); img.onload(); 

    1 answer 1

    Error 1: the context of the canvas should be set to the canvas itself, not the document, that is, instead of

    var context = document.getContext("2d")

    must be

    var context = canvas.getContext("2d")

    Error 2: the img definition occurs inside the getImage function, although by the img code it is used when the page is loaded, but it is not there, as a result of which an error occurs.

    Error 3: when loading the page, the initially selected select option is empty, there is nowhere to load the image. At the same time, there is no catching of changes in the selected option in the code, which means that when another image is selected, it cannot be loaded.

    Here is an example using jQuery: http://jsfiddle.net/bz4wgyqq/

    In pure javascript e: http://jsfiddle.net/0n6bz4cx/