Reputation: 48758
I've a nice bit of JS that creates falling confetti using the HTML canvas
-- but it only starts drawing if you resize the browser:
http://jsfiddle.net/JohnnyWalkerDesign/pmfgexfL/
Why is this?
Upvotes: 2
Views: 1188
Reputation: 9813
At initialization, you have:
canvas = document.getElementById("world");
context = canvas.getContext("2d");
window.w = 0;
window.h = 0;
which makes w
and h
for cofettis becomes (0, 0). It cause your Confetti.prototype.replace
to have useless xmax
and ymax
:
Confetti.prototype.replace = function() {
this.opacity = 0;
this.dop = 0.03 * range(1, 4);
this.x = range(-this.r2, w - this.r2);
this.y = range(-20, h - this.r2);
this.xmax = w - this.r; // -2 ~ -6
this.ymax = h - this.r; // -2 ~ -6
this.vx = range(0, 2) + 8 * xpos - 5;
return this.vy = 0.7 * this.r + range(-1, 1);
};
These makes its draw
function unable to draw something properly, as x and y would be invalid when x
or y
is greater that 0
.
Change it to
canvas = document.getElementById("world");
context = canvas.getContext("2d");
// Init the width and height of the canvas, and the global w and h.
window.w = canvas.width = window.innerWidth;
window.h = canvas.height = window.innerHeight;
See Altered Jsfiddle.
Upvotes: 1
Reputation: 3562
Your canvas width is only set inside the resizeWindow();
function.
Try adding resizeWindow();
directly after the function definition:
resizeWindow = function() {
window.w = canvas.width = window.innerWidth;
return window.h = canvas.height = window.innerHeight;
};
resizeWindow();
otherwise it doesn't get called until the page is resized.
http://jsfiddle.net/pmfgexfL/3/
Your window.onload
won't get called because it is inside confetti()
.
EDIT: As fuyushimoya pointed out, also remove the window.w = 0;
and window.h = 0;
lines since they're not required. I think that it is actually cleaner to set the size in a function on resize (as you do) in case you want to do something more custom, but you need to call it to initialize too.
http://jsfiddle.net/pmfgexfL/5/
Upvotes: 2