在javascript动画中创建许多类似的元素

creating many similar elements in javascript animation

本文关键字:元素 许多类 创建 javascript 动画      更新时间:2024-01-09

对于javascript动画,我正在尝试创建数字为1-9的按钮。现在我的数字1的javascript看起来像:

that1 = { thisx : 120, thisy: H-400, thisnumber= "1",
draw: function() {
    var keywidth = 100; 
    var keyheight = 150 ; 
    var x = this.thisx;
    var y = this.thisy;
    var cornercut = 5;
ctx.beginPath();
//drawing the key
ctx.moveTo(x, y+cornercut);
ctx.quadraticCurveTo(x,y, x+cornercut, y);
ctx.lineTo(x+keywidth-cornercut, y);
ctx.quadraticCurveTo(x+keywidth, y, x+keywidth, y+cornercut);
ctx.lineTo(x+keywidth, y+keyheight-cornercut);
ctx.quadraticCurveTo(x+keywidth, y+keyheight, x+keywidth-cornercut, y+keyheight);
ctx.lineTo(x+cornercut, y+keyheight);
ctx.quadraticCurveTo(x, y+keyheight, x, y+keyheight-cornercut);
ctx.lineTo(x, y+cornercut);
ctx.closePath();
ctx.stroke();
ctx.fillText(this.thisnumber, x+.5*keywidth,y+.8*keyheight); 
},
highlight: function() {
ctx.fillStyle="red";
ctx.fill();
} 
} ; 

我可以复制这个来创建this2、this3、this4、this5等等,但我觉得有一种更简单的方法。有人能帮忙吗?我使用JS是因为我相信这将是使用动画控制这些对象的最简单方法,但如果你有其他建议,请告诉我。

您可以更改thisxthisy的值,并简单地再次调用draw函数,但如果您简单地将这些值作为参数传递给draw函数,代码可能会更优雅。