Search code examples
javascriptpaperjs

Don't know how to apply raster to every planet in my code


I'm trying to draw planets on my canvas following a basic example on paper.js website, but when I want to use a raster in a for loop to apply "texture" to every one of them, only one planet gets the texture.

I've tried a couple solutions online, but none of them allowed me to make what I'm looking for. You will notice that, in my code, I have both planets (Points) and stars (Stars). The texture is a basic 100*100 square image.

        var url = '../IMG/planettexture.png';
        var raster = new Raster(url);

        var count = 150;
        var x = window.innerWidth;
        var y = window.innerHeight;

        for (i=0;i<count;i++){

            var xrandom = randomCoordinates(x);
            var yrandom = randomCoordinates(y);

            var center = new Point(xrandom,yrandom);

            var points = 12;

            var radius1 = randomCoordinates(1);
            var radius2 = randomCoordinates(5);
            var path = new Path.Star(center, points, radius1, radius2);
            path.fillColor = 'white';

            raster.position = new Point(xrandom,yrandom);
            path.clipMask = true;
        }

        var path = new Path.Circle({
            center: [0, 0],
            radius: 10,
            fillColor: 'white',
            strokeColor: 'black'
        });

        var symbol = new Symbol(path);

        for (var i = 0; i < count; i++) {
            var center = Point.random() * view.size;
            var placedSymbol = symbol.place(center);
            placedSymbol.scale(i / count);
        }

        function randomCoordinates(number){
            return Math.random()*number;
        }

        function onFrame(event) {

        for (var i = 0; i < 450; i++) {
            var item = project.activeLayer.children[i];

            item.position.x += item.bounds.width / 20;

            if (item.bounds.left > view.size.width) {
               item.position.x = -item.bounds.width;
            }
        }
    } 

You need Paper.js to run this. With this code, only one Star is "textured", the rest isn't visible on my screen. Do you have any idea where the problem is coming from ?


Solution

  • Don't you need to clone your raster inside the for loop ?

    var clonedRaster = raster.clone();
    clonedRaster.position = new Point(xrandom,yrandom);
    

    Here is a working example: https://codepen.io/JulienLemaitre/pen/PMmBNJ