+ 2
5 Respuestas
+ 2
You need to more practice & knowledge about canvas
https://code.sololearn.com/WA2oSg6Umk55/?ref=app
+ 2
Replace your JavaScript with this and it'll start showing your box with a random colour changed and moved slightly once per second:
window.onload = function(){
document.addEventListener("click", function(){
var x = Math.floor((Math.random() * window.innerWidth-20) + 10);
var y = 10;
var colors = ["lime", "tomato", "yellow", "pink", "orange"];
setInterval(function(){
y++;
var c = document.getElementById("myCanvas");
c.width=window.innerWidth-20;
c.height=window.innerHeight-20;
var ctx = c.getContext("2d");
ctx.beginPath();
var rand = Math.floor((Math.random() * 4) + 0);
ctx.fillStyle = colors[rand];
ctx.fillRect(x, y, 10, 25);
ctx.stroke();
}, 1000);
});
};
You should indent your code more consistently. It'll help a lot.
+ 1
Josh Greig that doesn't work really😅
+ 1
Josh Greig I want it to keep dropping randomly y. When user click
0
Michael, I tested it and it works on my computer.
If some code doesn't work, you should do a better job of identifying the problem than "it doesn't work". Steps to reproduce a bug or what you expected vs what actually happened would be much more helpful than "it doesn't work".
Maybe you just didn't click the document to start it.
Here is a version that starts animating without clicking anything.
window.onload = function(){
var x = Math.floor((Math.random() * window.innerWidth-20) + 10);
var y = 10;
var colors = ["lime", "tomato", "yellow", "pink", "orange"];
setInterval(function(){
y++;
var c = document.getElementById("myCanvas");
c.width=window.innerWidth-20;
c.height=window.innerHeight-20;
var ctx = c.getContext("2d");
ctx.beginPath();
var rand = Math.floor((Math.random() * 4) + 0);
ctx.fillStyle = colors[rand];
ctx.fillRect(x, y, 10, 25);
ctx.stroke();
}, 1000);
};