簡體   English   中英

HTML5 Canvas:帶有圖像疊加層的彈跳球

[英]HTML5 Canvas: Bouncing Balls with Image Overlay

我真的在HTML5畫布中遇到幾個問題。

我已將該項目發布到GitHub頁面( https://swedy13.github.io/ )並添加了一個圖像(圓圈在運動中),以便您可以看到問題。 基本上,如果向下滾動,頁面上會出現幾個綠色的圓圈。 我想用我的客戶徽標替換那些徽標。

HTML5 Canvas中的彈跳圓圈

我正在根據不同的操作從三個文件中調用requestAnimation,所有這些都可以在https://github.com/swedy13/swedy13.github.io/tree/master/assets/js中找到

文件名:-filter.js(使用過濾器時調用requestAnimation)-main.js(在加載和調整大小時)-Portfolio.js(這是畫布代碼所在的位置)

更新:我在下面添加了“ portfolio.js”代碼,因此答案可以獨立存在。

function runAnimation(width, height, type){
    var canvas  = document.getElementsByTagName('canvas')[0];
    var c = canvas.getContext('2d');

    // ---- DIMENSIONS ---- //
    // Container
    var x = width;
    var y = height - 65;
    canvas.width  = x;
    canvas.height = y;
    var container = {x: 0 ,y: 0 ,width: x, height: y};

    // Portrait Variables
    var cPos    = 200;
    var cMargin = 70;
    var cSpeed  = 3;
    var r       = x*.075;

    if (y > x && x >= 500) {
        cPos    = x * (x / y) - 150;
        cMargin = 150;
    }

    // Landscape Variables
    if (x > y) {
        cPos    = y * (y / x) - 50;
        cMargin = 150;
        cSpeed  = 3;
        r       = x*.05;
    }


    // ---- CIRCLES ---- //
    // Circles
    var circles = [];
    var img = new Image();

    // Gets active post ids and count
    var activeName  = [];
    var activeLogo  = [];
    var activePosts = $('.active').map(function() {
        activeName.push($(this).text().replace(/\s+/g, '-').toLowerCase());

        // Returns the image source
        /*activeLogo.push($(this).find('img').prop('src'));*/

        // Returns an image node
        var elem = document.getElementsByClassName($(this).text().replace(/\s+/g, '-').toLowerCase())
                            activeLogo.push(elem[0].childNodes[0]);
        });

        // Populates circle data
        for (var i = 0; i < $('.active').length; i++) {
            circles.push({
            id:activeName[i],
            r:r,
            color: 100,
            /*image: activeLogo[i],*/
            x:Math.random() * cPos + cMargin,
            y:Math.random() * cPos + cMargin,
            vx:Math.random() * cSpeed + .25,
            vy:Math.random() * cSpeed + .25
        });
    }

    // ---- DRAW ---- //
    requestAnimationFrame(draw);
    function draw(){
        c.fillStyle = 'white';
        c.fillRect(container.x, container.y, container.width, container.height);

        for (var i = 0; i < circles.length; i++){
            /*var img = new Image();
            var path = circles[i].image;*/
            /*var size = circles[i].r * 2;*/
            /*img.src = circles[4].image;*/
            var img = activeLogo[i];
            img.onload = function (circles) {
                /*c.drawImage(img, 0, 0, size, size);*/

                var pattern = c.createPattern(this, "repeat");
                c.fillStyle = pattern;
                c.fill();
            };

            c.fillStyle = 'hsl(' + circles[i].color + ', 100%, 50%)';
            c.beginPath();
            c.arc(circles[i].x, circles[i].y, circles[i].r, 0, 2*Math.PI, false);
            c.fill();


            // If the circle size/position is greater than the canvas width, bounce x
            if ((circles[i].x + circles[i].vx + circles[i].r > container.width) || (circles[i].x - circles[i].r + circles[i].vx < container.x)) {
                circles[i].vx = -circles[i].vx;
            }

            // If the circle size/position is greater than the canvas width, bounce y
            if ((circles[i].y + circles[i].vy + circles[i].r > container.height) || (circles[i].y - circles[i].r + circles[i].vy < container.y)){
                circles[i].vy = -circles[i].vy;
            }

            // Generates circle motion by adding position and velocity each frame
            circles[i].x += circles[i].vx;
            circles[i].y += circles[i].vy;
        }
        requestAnimationFrame(draw);
    }
}

現在,它的工作方式是:1.我的投資組合內容設置為“顯示:無”(最終,當他們單擊其中一個圓圈時,它將彈出一個窗口)。 2.畫布正在從DOM獲取投資組合對象,包括我無法使用的圖像。 3.如果使用“ onload()”函數,則可以使圖像顯示出來並在后台重復。 但這只是靜態背景-圓圈在其上方移動並顯示背景。 那不是我想要的

因此,基本上,我試圖找出如何將背景圖像附加到圓上(基於圓ID)。


-----------------更新-----------------

現在,我可以將圖像剪切到一個圓上並讓該圓在背景中移動。 但是它在頁面上不可見(我可以通過控制台記錄它的位置來知道它在移動)。 我唯一看到的是圓圈與圖像位置對齊,然后顯示出來。

function runAnimation(width, height, type){
    var canvas  = document.getElementsByTagName('canvas')[0];
    var c = canvas.getContext("2d");
    canvas.width = width;
    canvas.height = height;

    // Collects portfolio information from the DOM
    var activeName = [];
    var activeLogo = [];
    $('.active').map(function() {
        var text = $(this).text().replace(/\s+/g, '-').toLowerCase();
        var elem = document.getElementsByClassName(text);

        activeName.push(text);
        activeLogo.push(elem[0].childNodes[0]);
    });

    var img = new Image();
    img.onload = start;

    var circles = [];
    var cPos = 200;
    var cMargin = 70;
    var cSpeed = 3;
    for (var i = 0; i < 1; i++) {
        circles.push({
            id: activeName[i],
            img: activeLogo[i],
            size: 50,
            xPos: Math.random() * cPos + cMargin,
            yPos: Math.random() * cPos + cMargin,
            xVel: Math.random() * cSpeed + .25,
            yVel: Math.random() * cSpeed + .25,
        });
        img.src = circles[i].img;
    }

    requestAnimationFrame(start);
    function start(){
        for (var i = 0; i < circles.length; i++) {
            var circle = createImageInCircle(circles[i].img, circles[i].size, circles[i].xPos, circles[i].yPos);
            c.drawImage(circle, circles[i].size, circles[i].size);
                                            animateCircle(circles[i]);
        }

        requestAnimationFrame(start);
    }

    function createImageInCircle(img, radius, x, y){
        var canvas2 = document.createElement('canvas');
        var c2 = canvas2.getContext('2d');

        canvas2.width = canvas2.height = radius*2;

        c2.fillStyle = 'white';
        c2.beginPath();
        c2.arc(x, y, radius, 0, Math.PI*2);
        c2.fill();
        c2.globalCompositeOperation = 'source-atop';
        c2.drawImage(img, 0, 0, 100, 100);

        return(canvas2);
    }

    function animateCircle(circle) {
    // If the circle size/position is greater than the canvas width, bounce x
    if ((circle.xPos + circle.xVel + circle.size > canvas.width) || (circle.xPos - circle.size + circle.xVel < 0)) {
        console.log('Bounce X');
        circle.xVel = -circle.xVel;
    }

    // If the circle size/position is greater than the canvas width, bounce y
    if ((circle.yPos + circle.yVel + circle.size > canvas.height) || (circle.yPos + circle.yVel - circle.size < 0)) {
        console.log('Bounce Y');
        circle.yVel = -circle.yVel;
    }

    // Generates circle motion by adding position and velocity each frame
    circle.xPos += circle.xVel;
    circle.yPos += circle.yVel;
}
}

我不確定我是否正在制作正確的動畫。 我已經嘗試過對canvas2進行動畫處理,但這對我來說沒有任何意義。

PS-對不起GitHub格式,不知道為什么會這樣。 PPS-對我沒有清理的任何垃圾代碼表示歉意。 我已經嘗試了很多東西,並且可能丟失了一些更改的信息。 PPPS-請原諒我沒有使答案獨立。 我以為鏈接到GitHub會更有用,但是我已經更新了問題,以包含所有必要的信息。 感謝您的反饋。

讓您開始...

這是使用合成將圖像裁剪成圓形的方法。

該示例代碼創建了一個畫布徽標球,您可以將其重新用於每個彈跳球。

var logoball1=dreateImageInCircle(logoImg1,50);
var logoball2=dreateImageInCircle(logoImg2,50);

然后,您可以像這樣將每個徽標球繪制到主畫布上:

ctx.drawImage(logoball1,35,40);
ctx.drawImage(logoball2,100,75);

這里有許多關於Stackoverflow的示例,這些示例如何動畫畫布上的球,因此我將這一部分留給您。

 var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var cw=canvas.width; var ch=canvas.height; var img=new Image(); img.onload=start; img.src="https://dl.dropboxusercontent.com/u/139992952/m%26m600x455.jpg"; function start(){ var copy=createImageInCircle(img,50); ctx.drawImage(copy,20,75); ctx.drawImage(copy,150,120); ctx.drawImage(copy,280,75); } function createImageInCircle(img,radius){ var c=document.createElement('canvas'); var cctx=c.getContext('2d'); c.width=c.height=radius*2; cctx.beginPath(); cctx.arc(radius,radius,radius,0,Math.PI*2); cctx.fill(); cctx.globalCompositeOperation='source-atop'; cctx.drawImage(img,radius-img.width/2,radius-img.height/2); return(c); } 
 body{ background-color:white; } #canvas{border:1px solid red; } 
 <canvas id="canvas" width=512 height=512></canvas> 

暫無
暫無

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

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