简体   繁体   English

HTML5画布绘制在画布中移动的多个矩形

[英]HTML5 canvas draw multiple rectangles that move in the canvas

In this code i have a rectangle moving from the middle-left to the right at 30ticks, however, my brain hurts when i try to think how im going to add another square about the same size as the one antimated, but starting from a different direction. 在这段代码中,我有一个矩形,它在30ticks处从左中向右移动,但是,当我尝试思考如何添加与被匹配对象相同大小但又从另一个对象开始的另一个正方形时,我的大脑会受伤方向。 The issue is how i can add multiple objects, whether rectangle-circle and have it animate like the square in another starting xy location, here's what i have so far: 问题是我如何添加多个对象,无论是矩形圆形还是使其在另一个起始xy位置都像正方形一样具有动画效果,这就是我到目前为止所拥有的:

        var rectY=200, rectW=40;
        var rectX = -rectW;
        var canvas = null;
        var context = null;

        function init() {
            canvas = document.getElementById('testCanvas');
            context = canvas.getContext("2d");

            blank();

            context.fillStyle= "yellow";
            context.fillRect(rectX,rectY,rectW,rectW);
            setInterval(anim, 30);
        }

        function blank() {
            context.fillStyle = "#00ddee";
            context.fillRect(0,0,context.canvas.width, context.canvas.height);
        }

        function anim() {
            if (rectX < context.canvas.width) {
                blank();
                rectX += 5;
                context.fillStyle = "yellow";
                context.strokeStyle = "red";
                context.lineWidth = 3;
                context.fillRect(rectX,rectY,rectW,rectW);
                context.strokeRect(rectX,rectY,rectW,rectW);
            }
            else rectX=-rectW;
        }

Use JavaScript objects to represent multiple rectangles 使用JavaScript对象表示多个矩形

Here's an outline of how to do it: 以下是有关操作方法的概述:

  • Use a javascript object to describe each of your rectangles 使用javascript对象描述每个矩形
  • Put each rect object in a rects[] array 将每个rect对象放入rects []数组
  • Inside an animation loop: 在动画循环内:
    • Change each rect's x value 更改每个矩形的x
    • Redraw the canvas with the rects in their new positions 重新绘制画布,使rects处于新位置
    • Request another loop in the animation 请求动画中的另一个循环

Annotated code and a Demo: 带注释的代码和演示:

 var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var cw=canvas.width; var ch=canvas.height; // define a rect using a javascript object var rect1={ x:20, y:20, width:40, height:40, directionX:1 } // define another rect using a javascript object var rect2={ x:250, y:90, width:40, height:40, directionX:-1 } // put each rect in a rects[] array var rects=[rect1,rect2]; // start the animation loop requestAnimationFrame(animate); function animate(time){ // move each rect in the rects[] array by its // own directionx for(var i=0;i<rects.length;i++){ rects[i].x+=rects[i].directionX; } // draw all the rects in their new positions draw(); // request another frame in the animation loop requestAnimationFrame(animate); } function draw(){ ctx.clearRect(0,0,cw,ch); for(var i=0;i<rects.length;i++){ var r=rects[i] ctx.strokeRect(rx,ry,r.width,r.height); } } 
 body{ background-color: ivory; } #canvas{border:1px solid red; margin:0 auto; } 
 <canvas id="canvas" width=300 height=300></canvas> 

An improvement I leave for you to do is to stop the animation when all rectangles have left the visible canvas. 我要做的一项改进是在所有矩形都离开可见画布后停止动画。

This is the point of OOP (Object Orientated Programming), where each item in your program is represented as an object. 这就是OOP (面向对象编程)的重点,程序中的每个项目都表示为一个对象。 In your case we can have a Square object that has a: x, y, width, and color. 在您的情况下,我们可以拥有一个Square对象,该对象具有:x,y,宽度和颜色。 Along with a function to draw itself anim() : 连同一个用于绘制自身的函数anim()

function Square(x, y, w, color) 
{
    this.x = x;
    this.y = y;
    this.w = w;
    this.color = color;

    this.anim = function() 
    {
        if (this.x < context.canvas.width) {
            this.x += 5;
            context.fillStyle = this.color;
            context.strokeStyle = "red";
            context.lineWidth = 3;
            context.fillRect(this.x,this.y,this.w,this.w);
            context.strokeRect(this.x,this.y,this.w,this.w);
        }
        else this.x=-this.w;
    }
}

Then you can easily create objects, to animate each one place them inside an array and call anim() for each square in objects : 然后,您可以轻松创建对象,以动画化每个对象并将它们放置在数组中,并为objects每个正方形调用anim()

var rect1 = new Square(-40, 200, 40, "yellow");
var rect2 = new Square(0, 100, 40, "blue");
var objects = [ rect1, rect2 ];

setInterval(function(){
    blank();
    for(rect in objects){
        objects[rect].anim();
    }
}, 30);

Fiddle Example 小提琴的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM