canvas的簡單繪製及設定
阿新 • • 發佈:2020-09-21
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <style type="text/css"> #MyCanvas { border: 1px solid #f60; } </style> <body> <!--建立一個canvas標籤並設定大小--> <canvas id="MyCanvas" height="600" width="500"></canvas> </body> <script type="text/javascript"> //建立影象 var img = new Image(); img.src = 'img/0.png'; window.onload = function() { var MyCanvas = document.getElementById('MyCanvas');
//getContext() 方法返回一個用於在畫布上繪圖的環境,2d為二維繪圖 var ctx = MyCanvas.getContext('2d'); //開始繪製 ctx.beginPath();//設定填充影象,定位點X Y,寬高 ctx.rect(50, 50, 100, 100); //設定樣式 ctx.fillStyle = "red"; ctx.fill(); //影象陰影:1.陰影顏色2.X Y 為陰影方向3.模糊程度 ctx.shadowColor = "#FF6600"; ctx.shadowOffsetX = 10; ctx.shadowOffsetY = 10; ctx.shadowBlur= 5; //設定邊框 ctx.strokeStyle = 'lightblue'; ctx.stroke(); //開始一條路徑,或重置當前路徑 ctx.beginPath(); //影象位置移動 ctx.moveTo(500, 150); //繪製路徑 ctx.lineTo(300, 100); ctx.lineTo(300, 200); ctx.lineTo(300, 200); ctx.lineTo(300, 200); ctx.fillStyle = 'lightcoral'; ctx.fill(); ctx.beginPath(); ctx.moveTo(200, 50); ctx.lineTo(300, 100); ctx.lineTo(300, 200); ctx.lineTo(300, 200); ctx.lineTo(300, 200); ctx.fillStyle = 'lightcoral'; ctx.fill(); ctx.beginPath(); ctx.moveTo(400, 50); ctx.lineTo(300, 100); ctx.lineTo(300, 200); ctx.lineTo(300, 200); ctx.lineTo(300, 200); ctx.fillStyle = 'lightgreen'; ctx.fill(); ctx.beginPath(); ctx.moveTo(100, 250); ctx.lineTo(50, 300); ctx.lineTo(150, 300); //克隆一條邊框 ctx.closePath(); //邊框大小 ctx.lineWidth = 10; ctx.stroke(); ctx.strokeStyle = 'lightskyblue'; ctx.beginPath(); //中心點X Y,半徑r,起始弧度,結束弧度,true/false為半圓方向 //去掉'2*'為半圓 ctx.arc(250, 250, 50, 0, 2 * Math.PI); ctx.fill();; //放置文字 ctx.beginPath(); ctx.font = '30px 微軟雅黑'; ctx.fillText("Hello Canvsas", 50, 350); //文字描邊 ctx.beginPath(); ctx.lineWidth = 3; ctx.strokeText("Hello Canvsas", 50, 350); //放置圖片 ctx.beginPath(); ctx.drawImage(img, 50, 400, 150, 150); } </script> </html>