簡體   English   中英

嘗試將圖像放在畫布上的弧線內-javascript

[英]Trying to put an image inside an arc on canvas - javascript

嘿,我真的很希望有人在這里幫助我。 所以,基本上我只是在嘗試我的畫布技巧。 我想制作一個射擊游戲,用一堆表情符號在不同的y軸點,不同的高度上移動,並在x軸上以不同的速度滑動。

我有一些情緒圖像,我將其重命名為不可計數。 我掙扎的地方是在弧線內顯示圖像。 另外,我希望整個圖像以10 x 10 / etc顯示,而不僅僅是溢出。

我真的很想有人在這里幫助我,謝謝。

var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var height = canvas.height = window.innerHeight;
var width = canvas.width = window.innerWidth;
function random(min, max) {
    var num = Math.floor(Math.random() * (max - min)) + min;
    if (num === 0) {
       return 2;
    }
    return num;
}
function Target(x, y, velX, radius, image) {
    this.x = x;
    this.y = y;
    this.velX = velX;
    //this.velY = velY;
    this.radius = radius;
    this.image = image;
}
Target.prototype.update = function () {
    if (this.x + this.radius >= width) {
        this.velX = -this.velX;
    }
    if (this.x + this.radius <= width) {
        this.velX = -this.velX;
    }
    /*if (this.y + this.radius >= height) {
        this.velY = -this.velY;
    }
    if (this.y + this.radius >= 0) {
        this.velY = -this.velY;
    }*/
    this.x += this.velX;
    //this.y += this.velY; 
};
Target.prototype.draw = function () {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, true);
    ctx.fillStyle = ctx.createPattern(this.image, 'no-repeat');
    ctx.fill();


    this.update();
};


//var target1 = new Target(30, 40, 20, 20);
function loop() {
    ctx.fillRect(0, 0, width, height);
    var targets = [];
    var img = new Image();
    while (targets.length < 25) {
        img.src = './images/emogi' + random(1, 6) + '.jpg';
        img.repeat = 'no-repeat';
        img.maxHeight = 10;
        img.maxWidth = 10;
        var target = new Target(
            random(100, 500),
            random(100, 500),
            random(10, 30),
            20,
            img
        );
        targets.push(target);
    }
    for (var i =0; i< targets.length; i++) {
        target[i].draw();
        target[i].update();
    }
    requestAnimationFrame(loop);

}
loop();

您的問題是您看不到圖像。 發生這種情況是因為您開始加載圖像,然后立即繪制它。 繪制時沒有圖像。 尚未加載!

要修復它,您必須預加載所有圖像

Let images = {
    “emoji”: {}
};

function loadImages() {
    return new Promise((resolve, reject) => {
        // initiate loading
        // wait for all to load
        // resolve promise
    });
}

loadImages.then(startGame);

您可能會發現此問題對使用圖像填充畫布的Javascript / HTML5有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM