重复使用画布形状,而不是多次编写相同的代码

Reuse canvas shape instead of writing same code many times

本文关键字:代码 布形状      更新时间:2023-11-16

我目前正在学习画布,如果我想存储我的形状并创建其中的4个,但将它们放置在不同的位置或使用不同的颜色,我该怎么做?

http://jsfiddle.net/bp0bxgbz/50/

var x =  0;
var y = 15;
var speed = 5;
function animate() {
    reqAnimFrame = window.mozRequestAnimationFrame    ||
                window.webkitRequestAnimationFrame ||
                window.msRequestAnimationFrame     ||
                window.oRequestAnimationFrame
                ;
    reqAnimFrame(animate);
    x += speed;
    if(x <= 0 || x >= 475){
        speed = -speed;
    }
    draw();
}

function draw() {
    var canvas  = document.getElementById("ex1");
    var context = canvas.getContext("2d");
    context.clearRect(0, 0, 500, 170);
    context.beginPath();
    context.moveTo(x,y);
    context.lineTo(x + 105,y + 25);
    context.lineTo(x+25,y+105);
    context.fillStyle="red";
    context.fill();
}
animate();

创建4个对象——每个三角形一个。

每个对象都保持其1个三角形的当前x、y位置和当前速度。

您可以使用draw()函数中任意1个对象内部的信息在其当前x,y位置绘制1个三角形。

在动画功能中,可以使用4个对象中每个对象内部的信息来更改每个三角形的x位置。

var shapes=[];
shapes.push({x:10,y:10,speed:2});
shapes.push({x:10,y:125,speed:4});
shapes.push({x:10,y:250,speed:6});
shapes.push({x:10,y:375,speed:8});

在动画循环中,遍历数组,并通过将4个对象分别输入draw函数来绘制它们中的每一个。

context.clearRect(0, 0, 500, 170);
for(var i=0; i<shapes.length;i++){
    var s=shapes[i];
    s.x+=s.speed;
    if(s.x <= 0 || s.x >= 475){
        s.speed*=-1;
    }
    draw(s);
}

draw函数应该取指定的对象,并根据其指定的x、y和amp;速度值。

// create canvas & context variables once at the beginning of the script
var canvas  = document.getElementById("ex1");
var context = canvas.getContext("2d");
function draw(s) {
    context.beginPath();
    context.moveTo(s.x,s.y);
    context.lineTo(s.x + 105,s.y + 25);
    context.lineTo(s.x+25,s.y+105);
    context.fillStyle="red";
    context.fill();
}

注意:您可以创建画布&在脚本开始时使用一次上下文变量。无需在每次调用绘图时重新创建这些变量。此外,如果所有的绘图都是红色填充的,那么你也可以在脚本的开头设置一次。

示例代码和演示:

var context=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var shapes=[];
shapes.push({x:10,y:10,speed:2,color:'red'});
shapes.push({x:10,y:125,speed:4,color:'green'});
shapes.push({x:10,y:250,speed:6,color:'blue'});
shapes.push({x:10,y:375,speed:8,color:'gold'});
animate();
function animate(){
  context.clearRect(0,0,cw,ch);
  for(var i=0; i<shapes.length;i++){
    var s=shapes[i];
    s.x+=s.speed;
    if(s.x <= 0 || s.x >= cw){
      s.speed*=-1;
    }
    draw(s);
  }
  requestAnimationFrame(animate);
}
function draw(s) {
  context.beginPath();
  context.moveTo(s.x,s.y);
  context.lineTo(s.x + 105,s.y + 25);
  context.lineTo(s.x+25,s.y+105);
  context.fillStyle=s.color
  context.fill();
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=450></canvas>