12

I want to be able to click on a button on my page and load an image into a canvas at some X,Y coordinates?

The following code is what I have below. I would like the image to be in either image/photo.jpg or in the same directory but preferably in a subdirectory of the main page.

**Question: How to make a JPG show up in a canvas with the click of a button on the web page?

Code:

<!DOCTYPE html>
<html>

<script>
    function draw(){  
        var ctx = document.getElementById("myCanvas").getContext("2d");  
        var img = new Image():  
      //  img.src = "2c.jpg";  
        img.src = "/images/2c.jpg";  

        ctx.drawImage(img,0,0);  
    }


</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 6th, 2014 Code:

How is the following code not working. Do you have to have an ID tag on Canvas. The page will display but for some reason the image will not when the button is clicked. The image is in the same directory that my index.html file is in.

<!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>
1
  • var img = new Image: <- ; Commented Jan 9, 2018 at 23:34

1 Answer 1

18

Wait till the image is loaded before drawing:

var img = new Image();
img.onload = function(){        /*or*/  img.addEventListener("load", function(){
    ctx.drawImage(img,0,0);                 ctx.drawImage(img,0,0);
};                                      };
img.src = "/images/2c.jpg";  

Demo: http://jsfiddle.net/DerekL/YcLgw/


If you have more than one image in your game,

It is better to preload all images before it starts.

Preload images: http://jsfiddle.net/DerekL/uCQAH/ (Without jQuery: http://jsfiddle.net/DerekL/Lr9Gb/)


If you are more familiar with OOP: http://jsfiddle.net/DerekL/2F2gu/

function ImageCollection(list, callback){
    var total = 0, images = {};   //private :)
    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){
                callback && callback();
            }
        };
        img.src = list[i].url;
    }
    this.get = function(name){
        return images[name] || (function(){throw "Not exist"})();
    };
}

//Create an ImageCollection to load and store my images
var images = new ImageCollection([{
    name: "MyImage", url: "//example.com/example.jpg"
}]);

//To pick and draw an image from the collection:
var ctx = document.querySelector("canvas").getContext("2d");
ctx.drawImage(images.get("MyImage"), 0, 0);
Sign up to request clarification or add additional context in comments.

18 Comments

Does the image img.src come first or does the onload come first because how does it draw since the img.src is after the img.onload. I am not seeing it here.
Just tried it and it does not work either. I will past the new code or that script part above.
@user3376708 - onload should be first because your image will be start loading as soon as you set the src.
@user3376708 - Why are you setting the src twice?
@ThomasWeller JSFiddle automatically generates the full HTML with the JS and CSS inserted. Right click on the Result area and click "View frame source" to see the actual HTML.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.