试图获取画布中绘制的三个矩形在单击鼠标时垂直增长?

时间:2014-11-15 21:32:56

标签: javascript html5 canvas

我试图在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();

所有帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

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' tutorial。他使用间隔计时器每隔30ms刷新画布;在刷新时,画布的状态被验证,这意味着应用程序逻辑运行并每30ms重绘一次。