HappyQuest
HappyQuest

Reputation: 27

Images not rendering randomly on canvas

Image of the bug is appearing only at one place i.e. x = 0,y = 0.

var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var c = canvas.getContext('2d');
var bugSmashed = 0;

//rendering background image
function renderImage()
{
    var backImage = new Image();
    backImage.src = "jungle.jpg"
    backImage.onload = function(){
        c.drawImage(backImage,0,0,canvas.width,canvas.height)}
}
renderImage();

//Making a bug
class Bug {
    constructor(x,y){
        this.x = x;
        this.y = y;
    }
    renderBug(){
        var bugImage = new Image();
        bugImage.src = "bug.png";
        bugImage.onload = function(){
            c.drawImage(bugImage,this.x,this.y,65,65)}}
}

Trying to make the bug appear randomly on the canvas

var interval = setInterval(function(){
        var x = 32+Math.random()*(canvas.width-64);
        var y = 32+Math.random()*(canvas.height-64);
        var aBug = new Bug(x,y);
        aBug.renderBug();}, 2000);

I am sure I am missing something. Any help is appreciated. Thanks

Upvotes: 0

Views: 56

Answers (1)

Gershom Maes
Gershom Maes

Reputation: 8170

I found your problem: this changes its meaning inside a function. So when you use:

function(){c.drawImage(bugImage,this.x,this.y,65,65)}

this no longer refers to aBug! (It will instead refer to the global Window object.) You can use fat-arrow syntax instead (which preserves this):

() => c.drawImage(bugImage,this.x,this.y,65,65)

Another really ugly way which I discourage you from using is by creating a new reference to this, and then using that reference in your function:

let that = this;
function(){ c.drawImage(bugImage, that.x, that.y, 65, 65); };

Or you can simplify your code to have it gloss over onload logic, allowing you to avoid wrapping c.drawImage in a function in the first place (note the square which appears is a publicly addressable image):

var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var c = canvas.getContext('2d');

//Making a bug
let bugImg = new Image();
bugImg.src = "https://th.bing.com/th/id/OIP.pXD0MAw4LeAcVrt3qRiEfwAAAA?pid=ImgDet&rs=1";
class Bug {
    constructor(x,y){
        this.x = x;
        this.y = y;
    }
    renderBug(){
        c.drawImage(bugImg, this.x, this.y, 65, 65);
    }
}

var interval = setInterval(function(){
  var x = 32 + Math.random()* (canvas.width - 64);
  var y = 32 + Math.random()* (canvas.height - 64);
  var aBug = new Bug(x, y);
  aBug.renderBug();
}, 500);
<canvas id="canvas" width="100" height="100"></canvas>

Upvotes: 1

Related Questions