darzang
darzang

Reputation: 166

How to add a default image to a canvas but also let the user load his own image

I have a webpage that allows a user to load an image chosen from his file into a canvas with this code :

var canvas = $('#imageCanvas')[0];
var ctx = canvas.getContext('2d');

var imageLoader = $('#imageLoader')[0];
imageLoader.addEventListener('change', handleImage, false);
function handleImage(e){                                            
    var reader = new FileReader();
    reader.onload = function(event)
    {
        var img = new Image();
        img.onload = function()
        {
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img, 0, 0, img.width,img.height,0,0,canvas.width,canvas.height); 

        }
        img.src = event.target.result;

    }
    reader.readAsDataURL(e.target.files[0]);  

}

It works well, but what I'm trying to do is to set a default source for this canvas if the user doesn't upload any image, so that the canvas is loaded with the image from the default source in the first place, and the user can load his image later.

I know how to do both (default background, load an image) but I'm struggling when it comes to mix the two, and I didn't manage to find any similar question.

Tell me if you need more details/code, I thought only this would be necessary but I might be wrong Any help would be greatly appreciated !

Upvotes: 1

Views: 2077

Answers (1)

m87
m87

Reputation: 4523

You could accomplish something like that in the following way ...

var canvas = $('#imageCanvas')[0];
var ctx = canvas.getContext('2d');

var imageLoader = $('#imageLoader')[0];
imageLoader.addEventListener('change', handleImage, false);

// default image
var defImg = new Image();
defImg.src = "http://www.rhlaw.com/blog/wp-content/uploads/2011/10/kitten-300x300.jpg";
defImg.onload = function() {
    canvas.width = defImg.width;
    canvas.height = defImg.height;
    ctx.drawImage(defImg, 0, 0);
};
// user loaded image
function handleImage() {
    if (this.files && this.files[0]) {
        var reader = new FileReader();
        reader.onload = function(event) {
            var img = new Image();
            img.src = event.target.result;
            img.onload = function() {
                canvas.width = img.width;
                canvas.height = img.height;
                ctx.drawImage(img, 0, 0);
            };
        };
        reader.readAsDataURL(this.files[0]);
    }
}
#imageCanvas {
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="imageCanvas"></canvas>
<input type='file' id="imageLoader" accept="image/*">

Upvotes: 2

Related Questions