Reputation: 47
I want to have a canvas that randomly displays a different animal-head every time the window is refreshed. Thus, I am trying to push a random image from my head array onto my canvas. As you can see below, this is my array.
var heads = ['animals/dog.svg', 'animals/fish.svg', 'animals/monkey.svg'];`
And here is the draw image function that I want the array to randomly push an image to:
ctx.drawImage(img, 60, 50);
Here is the entirety of my code for context:
var heads = ['animals/dog.svg', 'animals/fish.svg', 'animals/monkey.svg'];
function gethead() {
var number = Math.floor(Math.random()*heads.length);
document.write('<img src="'+heads[number]+'" />');}
window.onload = function () {
var img = new Image();
img.src = 'dog.svg';
img.onload = function () {
// CREATE CANVAS CONTEXT.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 60, 50);
// DRAW THE IMAGE TO THE CANVAS.
}
}
Can anyone explain how I can make this work?
Upvotes: 0
Views: 809
Reputation: 3820
Create a img element and set src to heads[generatednumber] and append it to body.
var img=document.createElement('img');
img.src=heads[number];
document.body.append(img);
Using the same variable img
which has with reference to image,Write a function for onload callback
img.onload = function () { }
and in drawImage
pass the variable holding the reference of image i.e img
document.getElementById('canvas').getContext('2d').drawImage(img, 0,0);
Try running this snippet
var heads = ['https://cdn.pixabay.com/photo/2015/02/04/08/03/baby-623417__340.jpg', 'https://cdn.pixabay.com/photo/2018/03/11/20/42/mammals-3218028__340.jpg', 'https://cdn.pixabay.com/photo/2016/04/14/08/40/newborn-1328454__340.jpg'];
window.onload = function () {
let number = Math.floor(Math.random()*heads.length);
var img=document.createElement('img');
img.src=heads[number];
document.body.append(img);
img.onload = function () { document.getElementById('canvas').getContext('2d').drawImage(img, 0,0);
//remove the image after drawing
img.style.display="none"
}
}
<canvas id="canvas"></canvas>
Upvotes: 1