画布粒子的图片背景

时间:2016-05-03 19:36:53

标签: javascript canvas particles

我正在尝试为每个创建的粒子创建背景。 画布模式无法正常工作。我收到此错误>>
“SyntaxError:指定了无效或非法的字符串”
HTML

<canvas id="canvas"></canvas>

JS

(function(){

window.onload = function(){
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d'),
    particles = {},
    particleIndex = 0,
    particleNum = 1;

    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    ctx.fillStyle = '#000';
    ctx.fillRect(0, 0, canvas.width, canvas.width);

    function Particle(){
        this.x = canvas.width / 2;
        this.y = 0;
        this.vx = Math.random() * 10 - 5;
        this.vy = Math.random() * 10 - 5;
        this.gravity = 0.2;
        particleIndex++;
        particles[particleIndex] = this;
        this.id = particleIndex;
        this.test = 0;
        this.maxLife = 100;
    }
    Particle.prototype.draw = function(){
        this.x += this.vx;
        this.y += this.vy;
        this.vy += this.gravity;
        this.test++;
        if ( this.test >= this.maxLife ) {
            delete particles[this.id];
        };

        var img = new Image();
        img.src = 'img/aaa.png';
        var pattern = ctx.createPattern(img,'repeat');

        ctx.fillStyle = pattern;
        ctx.fillRect(this.x, this.y, 20, 20);
    };


    setInterval(function(){
        ctx.fillStyle = "#000";
        ctx.fillRect(0, 0, canvas.width, canvas.height);


        for (var i = 0; i < particleNum; i++) {
            new Particle();
        };

        for(var i in particles) {
            particles[i].draw();
        }

    },30)

}})();

我也试图用ctx.drawImage()来做这件事,但图片只显示了一次。

任何提示?:) Fiddle

1 个答案:

答案 0 :(得分:0)

我认为问题是图像的加载时间晚于使用它。

在你的平局()里面你有:

    var img = new Image();
    img.src = 'img/aaa.png';
    var pattern = ctx.createPattern(img,20,20);

每次想要绘制时创建新图像都是一个坏主意。我强烈建议你在draw循环之外创建img变量。设置图像的.src后,必须等到加载它才能使用它。您可以使用onload事件在准备好时通知您。

以下是一个例子:

 var imgLoaded = false;
 var img = new Image();
 img.src = 'img/aaa.png';
 img.onload = function() { imgLoaded = true; };

 function draw() {
   ...
   if (imgLoaded) {
       var pattern = ctx.createPattern(img, 'repeat');
       ...
   }
   ...
 }