Canvas的基本使用(一)

135 阅读1分钟
<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="200" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>

var c=document.getElementById("myCanvas");
//获取canvas的执行上下文
var ctx=c.getContext("2d");

// 绘制三个内部充满颜色的矩形
ctx.fillRect(50,50,200,100);

ctx.fillStyle="red"
ctx.fillRect(50,50,30,10);

ctx.fillStyle="green"
ctx.fillRect(10,10,30,10);

// 这里画线stoke的style样式设置与fill不一样
ctx.strokeStyle="red"; 
ctx.moveTo(1,1) // 起点坐标
ctx.lineTo(60,70) // 终点坐标
ctx.stroke()  //着色

//绘制居中的文本
ctx.fillStyle="white"
ctx.font = '30px 微软雅黑'
ctx.textAlign="center"   // 设置为center
ctx.fillText("测试一下",150,80);  // x轴坐标设置为宽度的一半 ,即可文本居中

//绘制空心矩形  
ctx.rect(40, 40, 120, 100) // 画一个矩形
ctx.strokeStyle="blue"; 
ctx.stroke(); // 绘制空心图案的时候需要

// 绘制空心文本
ctx.font="20px Georgia";
ctx.textAlign="start"   // 设置为center
ctx.strokeText('空心的字体', 40,30); // 画出来的是空心的文字


ctx.clearRect(10, 10, 60, 60); // 清除画布  先坐标,后长宽



</script>

</body>
</html>