canvas基本图形
Posted 卿若竹
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了canvas基本图形相关的知识,希望对你有一定的参考价值。
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>canvas</title> 6 <style> 7 body{ 8 margin:0;padding:0; 9 } 10 </style> 11 </head> 12 <body> 13 <canvas id="myCanvas" width="1080px" height="520px" style="border:1px dashed #000;" onmousemove="getCoordinates(event)" onmouseout="clearCoordinates()">你的浏览器不支持HTML5</canvas> 14 <div id="texts"></div> 15 </body> 16 <script type="text/javascript"> 17 //获取鼠标在canvas画布上的坐标,浏览器窗口左上角为原点 18 function getCoordinates(e){ 19 var x = e.clientX; 20 var y = e.clientY; 21 document.getElementById("texts").innerHTML = "Coordinates:("+ x +","+y+")"; 22 } 23 function clearCoordinates(){ 24 document.getElementById("texts").innerHTML = ""; 25 } 26 27 var c = document.getElementById("myCanvas"); 28 var cxt = c.getContext("2d"); 29 //画一个宽100px,高150px的矩形 30 cxt.beginPath(); 31 cxt.rect(0,0,100,150); 32 cxt.fillStyle="#ff0000"; 33 cxt.fill(); 34 cxt.closePath(); 35 36 //画一个三角形 37 cxt.beginPath(); 38 cxt.moveTo(110,0); 39 cxt.lineTo(210,150); 40 cxt.lineTo(110,150); 41 cxt.lineTo(110,0); 42 cxt.stroke(); 43 cxt.closePath(); 44 45 //画一个半圆 46 cxt.beginPath(); 47 cxt.arc(300,100,50,Math.PI,Math.PI*2,true); 48 cxt.fillStyle = "#00ff00"; 49 cxt.fill(); 50 cxt.closePath(); 51 52 //渐变 53 详见HTML5 Canvas进阶(一):渐变,透明,移动,旋转,缩放 54 55 /* 56 cxt.beginPath(); 57 cxt.arc(75,75,50,0,Math.PI*2,true); // 绘制 58 cxt.moveTo(110,75); 59 cxt.arc(75,75,35,0,Math.PI,false); // 口(顺时针) 60 cxt.moveTo(65,65); 61 cxt.arc(60,65,5,0,Math.PI*2,true); // 左眼 62 cxt.moveTo(95,65); 63 cxt.arc(90,65,5,0,Math.PI*2,true); // 右眼 64 cxt.stroke(); 65 */ 66 // 二次贝尔赛曲线 67 cxt.beginPath(); 68 cxt.moveTo(400,75); 69 cxt.quadraticCurveTo(400,50,450,50); 70 cxt.quadraticCurveTo(500,50,500,75); 71 cxt.quadraticCurveTo(500,100,450,100); 72 cxt.quadraticCurveTo(450,125,415,125); 73 cxt.quadraticCurveTo(435,125,435,100); 74 cxt.quadraticCurveTo(400,100,400,75); 75 cxt.stroke(); 76 cxt.closePath(); 77 78 /* // 封装的一个用于绘制圆角矩形的函数. 79 80 function roundedRect(ctx,x,y,width,height,radius){ 81 cxt.beginPath(); 82 cxt.moveTo(x,y+radius); 83 cxt.lineTo(x,y+height-radius); 84 cxt.quadraticCurveTo(x,y+height,x+radius,y+height); 85 cxt.lineTo(x+width-radius,y+height); 86 cxt.quadraticCurveTo(x+width,y+height,x+width,y+height-radius); 87 cxt.lineTo(x+width,y+radius); 88 cxt.quadraticCurveTo(x+width,y,x+width-radius,y); 89 cxt.lineTo(x+radius,y); 90 cxt.quadraticCurveTo(x,y,x,y+radius); 91 cxt.stroke(); 92 }*/ 93 94 95 96 97 </script> 98 </html>
以上是关于canvas基本图形的主要内容,如果未能解决你的问题,请参考以下文章