I want to click on the button on my page and upload the image to the canvas in some X, Y coordinates?
The following code is what I have below. I would like the image to be in any image / photo.jpg file or in the same directory, but preferably in a subdirectory of the main page.
** Question: How to make JPG appear on canvas with the click of a button on a web page?
code:
<!DOCTYPE html> <html> <script> function draw(){ var ctx = document.getElementById("myCanvas").getContext("2d"); var img = new Image(): </script> <body background="Black"> <div align="center"> <button type="button" onclick="draw()">Show Image on Canvas</button> <canvas id="myCanvas" width="900" height="400" style="border:2px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag. </canvas> </div> <script> var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.font="20px Arial"; ctx.fillText("Royal Flush $",500,50); ctx.fillText("Striaght Flush $",500,80); ctx.fillText("Flush $",500,110); ctx.fillText("Four of a Kind $",500,140); ctx.fillText("Full House $",500,170); ctx.fillText("Three of a Kind $",500,200); ctx.fillText("Two Pair $",500,230); ctx.fillText("Pair of ACES $",500,260); ctx.rect(495,10,270,350); ctx.stroke(); </script> </body> </html>
March 6, 2014 Code:
How the following code works. You must have an ID tag on the Canvas. The page will be displayed, but for some reason, the image will not be displayed when the button is pressed. The image is in the same directory as the index.html file.
<!DOCTYPE html> <html> <head> <title></title> </head> <style type="text/css"> canvas{ border: 5px solid black; } </style> </html> <button id="galaxy">Add image #1</button> <button id="circles">Add image #2</button><span></span> <canvas width="500" height="500"></canvas> <script> var Images = {}; function loadImages(list){ var total = 0; document.querySelector("span").innerText = "...Loading..."; for(var i = 0; i < list.length; i++){ var img = new Image(); Images[list[i].name] = img; img.onload = function(){ total++; if(total == list.length){ document.querySelector("span").innerText = "...Loaded."; } }; img.src = list[i].url; } } function drawImage(img){ var ctx = document.querySelector("canvas").getContext("2d"); ctx.drawImage(Images[img], 0, 0, 50, 50); } loadImages([{ name: "2c.jpg", url: "mp.jpg" },{ name: "mp.jpg", url: "mp.jpg" }]); document.querySelector("#galaxy").addEventListener("click", function(){ drawImage("galaxy"); }); document.querySelector("#circles").addEventListener("click", function(){ drawImage("weirdCircles"); }); </script> </html>