1. 程式人生 > >canvas基本圖形

canvas基本圖形

基本 ash tex spa set lang 移動 圓角矩形 tle

 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基本圖形