HTML画布仅在浏览器调整大小后触发?

时间:2015-10-29 18:45:24

标签: javascript html css canvas

我有一点点JS使用HTML canvas创建了下降的五彩纸屑 - 但它只在你调整浏览器大小时才开始绘制:

http://jsfiddle.net/JohnnyWalkerDesign/pmfgexfL/

调整大小之前:
enter image description here

调整大小后:
enter image description here

为什么会这样?

2 个答案:

答案 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;行,因为它们不是必需的。我认为在调整大小时设置函数的大小实际上更干净(如果你想做的话),以防你想要做更自定义的事情,但你也需要调用它来初始化。

http://jsfiddle.net/pmfgexfL/5/

答案 1 :(得分:1)

初始化时,你有:

canvas = document.getElementById("world");
context = canvas.getContext("2d");
window.w = 0;
window.h = 0;

使cofettis的wh变为(0,0)。这会导致Confetti.prototype.replace无用xmaxymax

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函数无法正确绘制内容,因为当xy大于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

相关问题