尝试在画布中绘制三个矩形以在单击鼠标时垂直增长

Trying To Get Three Rectangles Drawn In Canvas To Grow Vertically When Mouse Is Clicked?

本文关键字:单击 鼠标 垂直 布中 绘制 三个      更新时间:2023-09-26

每次用鼠标单击画布时,我都试图让HTML5的Canvas标签中打印的三个矩形垂直增长。

到目前为止,我的代码绘制了三个方块。 我有一个 growBy 函数,但是当我单击时,没有任何移动。 论坛会看看我的代码并告诉我哪里出错了吗?

谢谢

迈克尔

这是我的 HTML:

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8"/>
  <link href="styles.css" rel="stylesheet" type="text/css">
  </head>
 <body>
   <canvas id="canvas" width="400" height="400">
   <h3>Your Browser Does Not Support This Page.  Please Update To Latest Version.</h3>
   </canvas>
   <script type="application/javascript" src="script.js">
   </script>
 </body>
</html>

这是我的 CSS:

canvas  { 
border: 1px solid black; 
}

这是我的JavaScript:

// JavaScript For Canvas 
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var Square = function (x, y, width, height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
};
Square.prototype.growBy = function(amount) {
        this.height += amount;
        console.log("growing!");    
};
var DrawSquare = function (x, y, width, height) {
            Square.call(this, x, y, width, height);
};
DrawSquare.prototype = Object.create(Square.prototype);
DrawSquare.prototype.draw = function (color) {
            ctx.clearRect(this.x,this.y,this.width,this.height);
            ctx.fillStyle = color;
            ctx.fillRect (this.x, this.y, this.width,this.height);
};
var squareOne = new DrawSquare(0,375,25,25);
var squareTwo = new DrawSquare(40, 375, 25, 25);
var squareThree = new DrawSquare(80,375,25, 25);


var drawScene = function() {
    squareOne.draw("rgb(243, 83, 23)");
    squareTwo.draw("rgb(163, 187, 81)");
    squareThree.draw("rgb(38, 154, 214)");
};
document.getElementById("canvas").onclick = function() {
    console.log("hello!");
    squareOne.growBy(10);
    drawScene();
};
drawScene();

所有的帮助感谢!

http://jsfiddle.net/d3jht0bp/1/

Square.prototype.growBy = function(amount) {
    this.y -+ amount;
    this.height += amount;
    ctx.fillStyle = this.color;
    ctx.fillRect (this.x, this.y-amount, 
        this.width,this.height+amount);
};

您可以看到,我所做的只是在现有矩形的顶部绘制另一个矩形。我color对象的属性,以便我可以在此处访问它。

canvas是位图;我们只能绘制和擦除它——没有存储到其中的节点或对象。我推荐RaphaelJS,如果你想要一种更简单的方法来创建类似画布的对象并操作它们。但是,如果您想坚持使用canvas并了解有关使其动态化的更多信息,请查看Simon Sarris的教程。他使用间隔计时器每 30 毫秒刷新一次画布;刷新时,将验证画布的状态,这意味着应用逻辑每 30 毫秒运行并重绘一次。