HTML5、JavaScript和在画布中绘制多个矩形
为什么我的多个矩形不能在画布上绘制HTML5、JavaScript和在画布中绘制多个矩形,javascript,html,canvas,html5-canvas,Javascript,Html,Canvas,Html5 Canvas,为什么我的多个矩形不能在画布上绘制 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="Scripts/jquery-1.9.1.min.js"></script> </head> <body> <canvas
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.9.1.min.js"></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>
您的浏览器不支持画布
函数形状(x、y、w、h、填充){
这个.x=x;
这个。y=y;
这个.w=w;
这个,h=h;
this.fill=填充;
}
//获取画布元素。
var elem=document.getElementById('myCanvas');
//检查上下文是否存在
if(elem.getContext){
var myRect=[];
myRect.push(新形状(10,0,25,25,“#333”))
myRect.push(新形状(0,40,39,25,#333”))
myRect.push(新形状(0,80,100,25,#333”))
context=elem.getContext('2d');
for(myRect中的i){
//控制台日志(x);
context.fillRect(i.x,i.y,i.w,i.h)
}
////x,y,宽度,高度
//fillRect(0,0,50,50);
////x,y,宽度,高度
//fillRect(75,0,50,50);
}
谢谢你的帮助。你不需要给它填充颜色吗
context.fillStyle = i.fill;
context.fillRect(i.x,i.y,i.w,i.h);
好的,你就快到了。 当您在矩形数组中迭代时,您是在数组键上迭代,而不是在对象本身上迭代(请参见)。 另外,正如@jimjimmy1995所指出的,您需要使用
.fillStyle
as设置填充。fillRect
没有填充参数
此代码将在以下情况下工作:
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);
}
}
稍后我将看一看您的代码,但我只是想让您知道jCanvas插件jQuery大大简化了画布上的绘图。您可能想看一看。:)是的,你是对的-但这不是主要问题-在循环中获取数组值有问题。你似乎缺少一些行终止符。你有什么错误吗?呵呵,没问题;它会让你开始用分号来结束句子,而不仅仅是代码;:P