尝试在画布中绘制三个矩形以在单击鼠标时垂直增长
Trying To Get Three Rectangles Drawn In Canvas To Grow Vertically When Mouse Is Clicked?
每次用鼠标单击画布时,我都试图让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 毫秒运行并重绘一次。
相关文章:
- 单击鼠标,用MySQL数据填充html表单输入字段
- 如何防止用户使用javascript或jquery在链接中单击鼠标中键
- 单击鼠标时如何停止重复功能
- 单击鼠标在画布上绘制一个实心圆
- Jquery检测“;输入“;按键而不是单击鼠标
- 在YouTube视频上单击鼠标静音/取消静音
- 按下esc键或随机单击鼠标时,Jcrop失去焦点
- jquery键并单击鼠标
- 在边界外单击鼠标关闭弹出框
- 尝试在画布中单击鼠标以添加图像
- 如何避免在浏览器 JavaScript 中双击时(单击鼠标)处理
- 在 Firefox 中单击鼠标时无法选择所有输入元素文本
- 在淘汰赛中更改 css 类.js单击鼠标
- 在单击时对元素进行动画处理,并在该元素和其他元素上单击鼠标输入/鼠标离开
- 在jquery中单击鼠标
- 如何在网页上单击鼠标或鼠标悬停时播放部分音频文件
- 我的 js 函数在第二次单击鼠标后被调用
- 单击鼠标时文本输入更改类
- 有没有办法模拟每次单击鼠标左键时按 Ctrl 键
- 如何使用 Raphael.js 在每次单击鼠标时触发旋转动画