在画布内的弹跳上下文中绘制图像

时间:2013-05-05 02:09:09

标签: html5 canvas drawimage

编辑:解决上面的一些问题。

我正试图用html5,画布和一些jQuery弹跳图片。 我成功地制作了一些球弹跳,但我无法弄清楚如何绘制图片而不是简单的“粒子”。

我尝试过不同的方式,但实际上我认为她错过了什么。 我发布了整个HTML,因此您可以轻松地复制/粘贴它。

根据我的尝试,有一个评论部分有工作弹跳球。

非常感谢你!

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML5 Canvas Explode Demo</title>
<link rel="stylesheet" href="styles.css" />
<meta name="viewport" content="width=320 initial-scale=1.0, user-scalable=no" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<style type="text/css">
* {
    margin: 0; padding: 0;
}

html, body {
    width: 100%;
    height: 100%;
}

canvas {
    display: block;
    background: whiteSmoke;
    width: 100%;
    height: 100%;
}
#presentation{
    position: fixed;
    background: rgba(0,0,0,0.7);
    width: 100%;
    height: 70px;
    box-shadow: 7px 7px 13px rgba(0,0,0,0.3);
    color: white;
    font-family:futura;
    font-size: 30px;
    padding-left: 50px;
    padding-top: 10px;
}
</style>

</head>
<body>
<div id="presentation">Bouncing Baaaaalls!</div>
<canvas id="output" ></canvas>



<script type="text/javascript">


        (function() {
        window.requestAnimationFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.msRequestAnimationFrame||window.oRequestAnimationFrame||function(f){window.setTimeout(f,40/60)
            }}});

        var canvas = document.querySelector('canvas');
        var ctx = canvas.getContext('2d');

        function Particle() {
            var W = canvas.width = window.innerWidth;
            var H = canvas.height = window.innerHeight;
            this.radius = 20;
            this.x = parseInt(Math.random() * W);
            this.y = H;

            this.color = 'rgb(' +
            parseInt(Math.random() * 255) + ',' +
            parseInt(Math.random() * 255) + ',' +
            parseInt(Math.random() * 255) + ')';


            if (this.x > W/2 ){

                this.vx = Math.random() * (-15 - -5) + -5;

            }else{

                this.vx = Math.random() * (15 - 5) + 5;

            }


            this.vy = Math.random() * (-32 - -25) + -25;


            this.draw = function() {

                var img = new Image();
                img.src = 'troll1.png';
                ctx.beginPath();
                ctx.fillStyle = "rgb(255,255,255)";
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                ctx.closePath();

                ctx.beginPath();
                ctx.arc(this.x, this.y, 20, 0, 6.28, false); 
                ctx.clip(); 
                ctx.stroke();
                ctx.closePath();
                ctx.drawImage(img, 0, 0);

                //  WORKING PARTICLES STARTS HERE

                // ctx.fillStyle = this.color;

                // ctx.beginPath();

                // ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2, false);
                // ctx.fill();


                // ctx.closePath();

                //  WORKING PARTICLES ENDS HERE


            };

        }
        var particle_count = 20;  
        var particles = [];



        // Now lets quickly create our particle
        // objects and store them in particles array
        for (var i = 0; i < particle_count; i++) {
            var particle = new Particle();
            particles.push(particle);
        }

        function renderFrame() {


            requestAnimationFrame(renderFrame);

            // Clearing screen to prevent trails
            var W = canvas.width = window.innerWidth;
            var H = canvas.height = window.innerHeight;
            ctx.clearRect(0, 0, W, H);

            particles.forEach(function(particle) {

                // The particles simply go upwards
                // It MUST come down, so lets apply gravity
                particle.vy += 1;

                // Adding velocity to x and y axis
                particle.x += particle.vx;
                particle.y += particle.vy;

                // We're almost done! All we need to do now
                // is to reposition the particles as soon
                // as they move off the canvas.
                // We'll also need to re-set the velocities

                if (
                    // off the right side
                    particle.x + particle.radius > W ||
                    // off the left side
                    particle.x - particle.radius < 0 ||
                    // off the bottom
                    particle.y + particle.radius > H
                ) {

                    // If any of the above conditions are met
                    // then we need to re-position the particles
                    // on the base :)


                    // If we do not re-set the velocities then
                    // the particles will stick to base :D

                    // Velocity X
                    particle.x = parseInt(Math.random() * W);
                    particle.y = H;
                    if (particle.x > W/2 ){

                        particle.vx = Math.random() * (-15 - -5) + -5;

                    }else{

                        particle.vx = Math.random() * (15 - 5) + 5;


                    }
                    particle.vy = Math.random() * (-32 - -28) + -28;


                }

                particle.draw();

            });
        }

        $(document).ready(function(){


            renderFrame();

        }); 


</script>
</body>
</html>

使用解决方案进行编辑: 首先,感谢markE

我按照他的说法编辑了代码,问题实际上是关于时间安排(并理解我在做什么)。他的回答对我很有帮助。

图像没有移动,因为我没有告诉它实际上这样做(使用ctx.drawImage(img,this.x,this.y))。

注意:有关使用chrome调试画布渲染,请查看HTML5 canvas inspector?

所以这里是弹跳巨魔面孔的工作(以及超评论,感谢课程标记E)(将troll1.png图片放在同一个文件夹中):

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML5 Canvas Explode Demo</title>
<!--    <link rel="stylesheet" href="styles.css" /> --> <meta name="viewport" content="width=320 initial-scale=1.0, user-scalable=no" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<style type="text/css">
* {
    margin: 0; padding: 0;
}

html, body {
    width: 100%;
    height: 100%;
}

canvas {
    display: block;
    background: whiteSmoke;
    width: 100%;
    height: 100%;
}
#presentation{
    position: fixed;
    background: rgba(0,0,0,0.7);
    width: 100%;
    height: 70px;
    box-shadow: 7px 7px 13px rgba(0,0,0,0.3);
    color: white;
    font-family:futura;
    font-size: 30px;
    padding-left: 50px;
    padding-top: 10px;
}
</style>

</head>
<body>
<div id="presentation">Bouncing Baaaaalls!</div>
<canvas id="output" ></canvas>



<script type="text/javascript">


(function() {
    //define the animation refresh (frame rendering) with built-in browser timing
    window.requestAnimationFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.msRequestAnimationFrame||window.oRequestAnimationFrame||function(f){window.setTimeout(f,40/60)
        }}});

//define some variables: canvas, context, img to put inside the context and an array of bouncing objects
        var canvas = document.querySelector('canvas');
        var ctx = canvas.getContext('2d');
        var img = new Image();
        //IMPORTANT: Wait for the picture to be loaded!
        img.onload = function(){
                alert('troll1 is LOADED.');

                beginAnimation();
        };
        //yes, the src goes after
        img.src = 'troll1.png';

        //how many bouncing objects?
        var particle_count = 4;  
        var particles = [];
        var particle;

        function Particle() {

            //define properties of a bouncing object, such as where it start, how fast it goes

            var W = canvas.width = window.innerWidth;
            var H = canvas.height = window.innerHeight;
            this.radius = 20;
            this.x = parseInt(Math.random() * W);
            this.y = H;

            //Uncomment for coloured particles: 

            // this.color = 'rgb(' +
            // parseInt(Math.random() * 255) + ',' +
            // parseInt(Math.random() * 255) + ',' +
            // parseInt(Math.random() * 255) + ')';

            //end coloured particles

            if (this.x > W/2 ){

                this.vx = Math.random() * (-15 - -5) + -5;

            }else{

                this.vx = Math.random() * (15 - 5) + 5;

            }


            this.vy = Math.random() * (-32 - -25) + -25;

            //we will call this function to actually draw the bouncing object at EVERY FRAME

            this.draw = function() {
                // Bouncing pictures were not bouncing because there were no this.x this.y . Shame on me. 

                 ctx.drawImage(img,this.x,this.y);


                // WORKING PARTICLES STARTS HERE

                // ctx.fillStyle = this.color;

                // ctx.beginPath();

                // ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2, false);
                // ctx.fill();


                // ctx.closePath();

                //WORKING PARTICLES ENDS HERE


            };

        }



        function renderFrame() {

            //RENDER THE PARTICLEEEEEEES!

            requestAnimationFrame(renderFrame);

            // Clearing screen to prevent trails
            var W = canvas.width = window.innerWidth;
            var H = canvas.height = window.innerHeight;
            ctx.clearRect(0, 0, W, H);

            particles.forEach(function(particle) {

                // The bouncing objects simply go upwards
                // It MUST come down, so lets apply gravity
                particle.vy += 1;

                // Adding velocity to x and y axis
                particle.x += particle.vx;
                particle.y += particle.vy;

                // We're almost done! All we need to do now
                // is to reposition the bouncing objects as soon
                // as they move off the canvas.
                // We'll also need to re-set the velocities

                if (
                    // off the right side
                    particle.x + particle.radius > W ||
                    // off the left side
                    particle.x - particle.radius < 0 ||
                    // off the bottom
                    particle.y + particle.radius > H
                ) {

                    // If any of the above conditions are met
                    // then we need to re-position the bouncing objects
                    // on the base :)


                    // If we do not re-set the velocities then
                    // the bouncing objects will stick to base :D

                    // Velocity X
                    particle.x = parseInt(Math.random() * W);
                    particle.y = H;
                    if (particle.x > W/2 ){

                        particle.vx = Math.random() * (-15 - -5) + -5;

                    }else{

                        particle.vx = Math.random() * (15 - 5) + 5;


                    }
                    particle.vy = Math.random() * (-32 - -28) + -28;


                }

                particle.draw();

            });
        }

        function beginAnimation(){
                    //create the particles and start to render them

                   for (var i = 0; i < particle_count; i++) {
                        particle = new Particle();
                        particles.push(particle);
                    }

                    //BOUNCE MOFOS!
                    renderFrame();

            }


</script>

   

1 个答案:

答案 0 :(得分:1)

在尝试绘制之前,你不是在等待troll1.png加载。

Var img=new Image();
img.onload=function(){
        beginMyAnimation();
}
img.src=”troll1”;
alert(“troll1 is not loaded yet.”);
function beginAnimation(){
        ….
        ctx.drawImage(img,0,0);
        ….
}

执行顺序如下:

首先 var img=new Image()

Javascript创建一个新的图像对象并在img中添加引用。

第二次 img.onload…

Javascript尚未执行此代码。需要注意的是,必须在troll1.jpg成功加载到新图像对象后执行onload。

第三次 img.src=”something.jpg”

Javascript立即开始加载troll1.jpg。

由于加载需要一段时间,Javascript 也会继续执行后面的任何代码。

第四 alert(“Image is not loaded yet.”);

Javascript显示此警报消息。请注意,troll1.jpg 尚未加载。因此,现在尝试使用该图像的任何代码都将失败 - 无图像!

第五 img.onload

Javascript终于完全加载了troll1.jpg,因此它执行onload函数。

第六次 beginMyAnimation()

Javascript最终将执行beginAnimation()。此时,尝试使用该图像的任何代码都将成功。你可以做ctx.drawImage(img,0,0)现在就会成功。

因此,在beginAnimation()中重新排列所有设置代码。最后,将renderFrame()放在beginAnimation()的最后。