我有一点点JS使用HTML canvas
创建了下降的五彩纸屑 - 但它只在你调整浏览器大小时才开始绘制:
http://jsfiddle.net/JohnnyWalkerDesign/pmfgexfL/
为什么会这样?
答案 0 :(得分:2)
您的画布宽度仅在resizeWindow();
函数内设置。
尝试在函数定义后直接添加resizeWindow();
:
resizeWindow = function() {
window.w = canvas.width = window.innerWidth;
return window.h = canvas.height = window.innerHeight;
};
resizeWindow();
否则在调整页面大小之前不会调用它。
http://jsfiddle.net/pmfgexfL/3/
您的window.onload
将不会被调用,因为它位于confetti()
内。
编辑:正如fuyushimoya指出的那样,也删除了window.w = 0;
和window.h = 0;
行,因为它们不是必需的。我认为在调整大小时设置函数的大小实际上更干净(如果你想做的话),以防你想要做更自定义的事情,但你也需要调用它来初始化。
答案 1 :(得分:1)
初始化时,你有:
canvas = document.getElementById("world");
context = canvas.getContext("2d");
window.w = 0;
window.h = 0;
使cofettis的w
和h
变为(0,0)。这会导致Confetti.prototype.replace
无用xmax
和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);
};
这使得draw
函数无法正确绘制内容,因为当x
或y
大于0
时,x和y将无效。
将其更改为
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;
请参阅Altered Jsfiddle。