If you watch the previous example carefully (go back if you need to), you may notice sometimes the watermelon is too far to the right. That's because of this line:
melon_x= Math.random() * myCanvas.width;
Recall that
Math.random() returns a random number between 0 and 0
.9999. When you multiply that result by
myCanvas.width, you obviously end up with a number between zero and whatever the width of the canvas is. All good.
But also recall that the co-ordinates passed to ctx.drawImage specify the top-left corner of the image.
So if the x-position can be all the way over to the canvas width, the image might sometimes be drawn partly outside the visible canvas.
The solution is to arrange for the x-position to be between zero and the
canvas width less the image width:
melon_x= Math.random() * (myCanvas.width - MelonImg.width);
Now the watermelon is always completely visible.