HTML5, JavaScript and drawing multiple rectangles in a canvas(HTML5、JavaScript 和在画布中绘制多个矩形)
问题描述
为什么我的多个矩形不能在画布中绘制?
Why won't my multiple rectangles draw in the canvas?
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="U2NyaXB0cy9qcXVlcnktMS45LjEubWluLmpz"></script>
</head>
<body>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid red">
<p>Your browser doesn't support canvas.</p>
</canvas>
</body>
</html>
<script type ="text/javascript">
function Shape(x, y, w, h, fill) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.fill = fill;
}
// get canvas element.
var elem = document.getElementById('myCanvas');
// check if context exist
if (elem.getContext) {
var myRect = [];
myRect.push(new Shape(10, 0, 25, 25, "#333"))
myRect.push(new Shape(0, 40, 39, 25, "#333"))
myRect.push(new Shape(0, 80, 100, 25, "#333"))
context = elem.getContext('2d');
for (i in myRect) {
//console.log(x);
context.fillRect(i.x, i.y, i.w, i.h)
}
//// x, y, width, height
//context.fillRect(0, 0, 50, 50);
//// x, y, width, height
//context.fillRect(75, 0, 50, 50);
}
</script>
感谢您的帮助.
推荐答案
好的,你就快到了.当您遍历矩形数组时,您是在遍历数组 key 而不是对象本身(请参阅 如何以对象为成员循环遍历纯 JavaScript 对象?).另外,正如@jimjimmy1995 指出的那样,您需要使用 .fillStyle
设置填充.fillRect
没有填充参数.
Ok, so you were almost there.
When you iterate round your array of rectangles, you are iterating over the array key not the objects themselves (see How to Loop through plain JavaScript object with objects as members?).
Plus, as @jimjimmy1995 pointed out, you need to set the fill using .fillStyle
as .fillRect
does not have a fill parameter.
此代码将起作用:
function Shape(x, y, w, h, fill) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.fill = fill;
}
// get canvas element.
var elem = document.getElementById('myCanvas');
// check if context exist
if (elem.getContext) {
var myRect = [];
myRect.push(new Shape(10, 0, 25, 25, "#333"));
myRect.push(new Shape(0, 40, 39, 25, "#333"));
myRect.push(new Shape(0, 80, 100, 25, "#333"));
context = elem.getContext('2d');
for (var i in myRect) {
oRec = myRect[i];
context.fillStyle = oRec.fill;
context.fillRect(oRec.x, oRec.y, oRec.w, oRec.h);
}
}
这篇关于HTML5、JavaScript 和在画布中绘制多个矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:HTML5、JavaScript 和在画布中绘制多个矩形


- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01