繁体   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