今天整画布,半天下来老是错,结果:
<canvas id = 'c1' width="400" height="400">
<p>浏览器不支持</p><!--width:300 height:150-->
</canvas>
原来画布的宽度和高度需要在标签定义的时候确定,并且后面是不能带有px这个单位的,比如:
错误的定义:
#c1
{
background: white;
position: absolute;
left: 200px;
top: 10px;
width:400px;
height:400px;
}
oGC.fillStyle = 'yellow';
oGC.fillRect(10,10,200,100);//(x,y,w,h)这个是画一矩形,默认的填充的是黑色
还应该知道的是这样矩形填充的颜色必须在画矩形之前做
oGC.strokeStyle = 'red';//这个是表示划线的颜色设置
这个也是画一个矩形,这个是默认没有填充的,或者说是白色的
oGC.strokeRect(10.5,100.5,100,80);
oGc.fillStyle="green";
oGc.strokeStyle="red";
oGc.beginPath();//声明
oGc.moveTo(10,20);//开始位置
oGc.lineTo(60,80);//目标位置
oGc.stroke();
oGc.lineTo(100,190);
oGc.stroke();
oGc.lineTo(10,20);
oGc.stroke();fill();//想要填充指定的颜色,需要用到fillStyle="green"
// 还有就是fill(),并且这个fill()是必须在所有的stroke执行之后才进行执行的oGc.closePath();在画布上面画线是,首先是beginPath(),moveTo是起点,lineTo是下一个点
stroke()是表示执行画
<!DOCTYPE html>
<html lang="en">
<head>
<!--画布-->
<meta charset="UTF-8">
<title>Canvas</title>
<style>
body
{
background: gray;
}
#c1
{
background: white;
position: absolute;
left:200px;
top:20px;
/*box-shadow: 4px 4px 4px black;*/
}
</style>
<script>
window.onload=function(){
// 获取画布
var oCan=document.getElementById("c1");
var oGc=oCan.getContext("2d");
// oGc.fillStyle="yellow";//给内部填充颜色
// oGc.fillRect(10,10,200,100);//画一个矩形默认的填充为黑色
// 填充一个矩形,坐标,宽和高
// oGc.fillStyle='red';//填充矩形要在该矩形画之前进行
// oGc.fillRect(0,0,100,50);
// oGc.strokeStyle="red";
// oGc.strokeRect(10.5,100.5,100,80);//前面是
// oGc.strokeRect(10.5,100.5,100,80);
//
// oGc.strokeText("你好");
oGc.fillStyle="green";
oGc.strokeStyle="red";
oGc.beginPath();//声明
oGc.moveTo(10,20);//开始位置
oGc.lineTo(60,80);//目标位置
oGc.stroke();
oGc.lineTo(100,190);
oGc.stroke();
oGc.lineTo(10,20);
oGc.stroke();
oGc.fill();//想要填充指定的颜色,需要用到fillStyle="green"
// 还有就是fill(),并且这个fill()是必须在所有的stroke执行之后才进行执行的
oGc.closePath();
}
</script>
</head>
<body>
<canvas id="c1" width="400" height="400">
<!--默认的大小是width=300,height=150-->
</canvas>
</body>
</html>