Как сделать текст на переднем плане с повторяющимся узором на холсте? - PullRequest
3 голосов
/ 18 апреля 2020

Я пытаюсь получить повторное фоновое изображение с текстом на переднем плане, но когда я добавляю узор на холст, текст не виден, вот мой код:
HTML

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

JavaScript

        var canvas = document.getElementById("canvas");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        var ctx = canvas.getContext("2d");
        var img = new Image();
        img.src = "https://cdn.pixabay.com/photo/2019/03/03/20/23/flowers-4032775__340.png";
        img.height = 10;
        img.onload = function(){
            ctx.font = "30px Calibri";
            ctx.fillText("DEXIE", 10, 50);
            ctx.drawImage(img, 0, 0);
            var ptrn = ctx.createPattern(img, 'repeat');
            ctx.fillStyle = ptrn;
            ctx.fillRect(0, 0, canvas.width, canvas.height);
        }

1 Ответ

1 голос
/ 19 апреля 2020

Нарисуйте текст после рисования рисунка. Изменение fillStyle на цвет, которым вы хотите, чтобы текст был.

    canvas.width = innerWidth;
    canvas.height = innerHeight;
    var ctx = canvas.getContext("2d");
    var img = new Image();
    img.src = "https://cdn.pixabay.com/photo/2019/03/03/20/23/flowers-4032775__340.png";
    img.onload = function(){
        img.height = 10;            
        ctx.drawImage(img, 0, 0);  // Do you really want to draw the image on the canvas????
        var ptrn = ctx.createPattern(img, 'repeat');

        // Draw pattern first
        ctx.fillStyle = ptrn;
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // Draw text on top
        ctx.font = "30px Calibri";
        ctx.fillStyle = "Black";        // <<== Set text color
        ctx.fillText("DEXIE", 10, 50);

    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...