Friday, 25 October 2019

replace CanvasRenderingContext rectangles, shapes with svg images in browser Pacman game

I'm trying to replace the pills in this browser game with svg images

https://codepen.io/hellokatili/pen/xwKRmo

At the top of the JS file, I entered the following (my approach is based on this answer):

var image = new Image()
img.src = "http://upload.wikimedia.org/wikipedia/commons/d/d2/Svg_example_square.svg";

There is a function called drawPills which draws the pills using CanvasRenderingContext rectangles. As I understand it, the image I want to replace these rectangles with needs to be loaded before I can use it, so I replace the call to drawPills() with the following:

    image.onload = function() {
      map.drawPills(ctx);

    }

Then in the drawPills() function, I replace the rectangles with the image:

      ctx.drawImage(image, i, j);

Here's what my completed version of drawPills looks like:

  function drawPills(ctx) { 

    if (++pillSize > 30) {
        pillSize = 0;
    }

    for (i = 0; i < height; i += 1) {
        for (j = 0; j < width; j += 1) {
            if (map[i][j] === Pacman.PILL) {
              ctx.drawImage(image, i, j);
              /*                     ctx.beginPath();

                ctx.fillStyle = "#000";
                ctx.fillRect((j * blockSize), (i * blockSize), 
                             blockSize, blockSize);

                ctx.fillStyle = "#FFF";
                ctx.arc((j * blockSize) + blockSize / 2,
                        (i * blockSize) + blockSize / 2,
                        Math.abs(5 - (pillSize/3)), 
                        0, 
                        Math.PI * 2, false); 
                ctx.fill();
                ctx.closePath();*/

            }
        }
    }

No svgs are loaded, however. Can anyone help me figure out what I'm doing wrong?



from replace CanvasRenderingContext rectangles, shapes with svg images in browser Pacman game

No comments:

Post a Comment