<canvas> - 定义使用 JavaScript 的图像绘制。
p.s.
<<canvas.js>>
function draw(elem) { // 1.获取canvas元素 var canvas = document.getElementById(elem); canvas.width = "600"; canvas.height = "500"; // 2.取得上下文 var context = canvas.getContext('2d'); // 3.填充与绘制边框 context.fillStyle = '#000'; // 4.设置绘制样式 context.strokeStyle = '#f60'; // 5.指定画笔宽度 context.lineWidth = 3; // 7.绘制矩形 context.fillRect(100,0,300,400); context.strokeRect(130,100,180,120);}<<index.html>>
<!DOCTYPE html><html><head> <title>canvas</title> <script type="text/javascript" src="canvas.js"></script></head><body> <!-- 通过draw函数进行绘图 --> <!-- 定义画布 --> <!-- <canvas></canvas> --> <canvas></canvas></body></html>————————————————————————————————————————————
Demo2 - 绘制圆形
步骤:
<<canvas.js>>
function draw(elem) { var canvas = document.getElementById('canvas'); canvas.width = 600; canvas.height = 500; var context = canvas.getContext('2d'); context.fillStyle = "#eeefff"; context.fillRect(0, 0, 600, 500); for (var i = 0; i < 10; i++) { context.beginPath(); // 创建开始路径 context.arc(i * 20, i * 30, i * 10, 0, Math.PI * 2, true); // 创建图形路径 context.closePath(); // 创建完成关闭路径 context.fillStyle = "rgba(255,0,0,0.25)"; // 路径样式 context.fill(); }}————————————————————————————————————————————
Demo3 - 绘制文字
<<canvas.js>>
function draw(elem) { var canvas = document.getElementById('canvas'); canvas.width = 800; canvas.height = 300; context = canvas.getContext('2d'); context.fillStyle = "green"; context.fillRect(0, 0, 800, 300); // 设置文字颜色 context.fillStyle = "#fff"; context.strokeStyle = "#fff"; // 设置字体 context.font = "bold 40px 'KaiTi','SimSun','Microsoft YaHei'"; // 设置对齐方式 context.textAlign = 'start'; context.textBaseline = 'Bottom'; // 设置内容 context.fillText('绘制文字', 200, 50); // 填充方式 context.strokeText('绘制文字', 100, 150); // 轮廓方式 context.fillText('1111111111111111111111111111111111111111111', 200, 250, 500); // 防止溢出,超过宽度时会压缩}————————————————————————————————————————————
Demo4 - 保存文件
Canvas API保存文件是通过绘画状态动态输出到一个data URL地址所指向的数据的过程
toDataURL()方法
<<canvas.js>>
1 function draw(elem) {2 var canvas = document.getElementById(elem);3 canvas.width = 800;4 canvas.height = 500;5 var context = canvas.getContext('2d');6 context.fillStyle = "#eeefff";7 context.fillRect(0,0,800,500);8 window.location = canvas.toDataURL('image/jpeg');9 }————————————————————————————————————————————
Demo5 - 简单动画
HTML DOM setInterval() 方法
<<canvas.js>>
function draw(elem) { var canvas = document.getElementById(elem); canvas.width = 800; canvas.height = 500; var context = canvas.getContext('2d'); context.fillStyle = "#eeefff"; context.fillRect(0, 0, 800, 500); context.fillStyle = '#f90'; // 画布擦除一部分 context.clearRect(50, 50, canvas.width - 50, canvas.height - 50); // 每100ms执行一次painting()函数,绘制一个新的小方框 var i = 0; var paintId = setInterval(painting, 100); function painting() { ++i; context.fillRect(80 + i * 15, 80, 10, 10); if (i == 20) { clearInterval(paintId); } }}