แท็ก canvas ใน HTML ใช้สำหรับวาดกราฟิก เพื่อวาดกราฟิก คุณต้องใช้ script แท็กนี้ introduced ใน HTML5 ทุก canvas มี 2 องค์ประกอบที่อธิบายความสูงและความกว้าง คือ height และ width ตามลำดับ
แอตทริบิวต์ต่อไปนี้:
- height — ความสูงของ canvas ในพิกเซล
- width — ความกว้างของ canvas ในพิกเซล
มาดูตัวอย่างการใช้ canvas tag ใน HTML:
ตัวอย่าง
<!DOCTYPE html>
<html>
<body>
<canvas id="newCanvas" width="600" height="350" style="border: 2px solid orange;">
</canvas>
<script>
var c = document.getElementById("newCanvas");
var ctx = c.getContext("2d");
ctx.shadowBlur = 20;
ctx.shadowColor = "black";
ctx.fillStyle = "green";
ctx.fillRect(40, 40, 100, 250);
ctx.shadowBlur = 30;
ctx.shadowColor = "blue";
ctx.fillStyle = "orange";
ctx.fillRect(200, 40, 200, 150);
</script>
</body>
</html>
ผลลัพธ์

มาดูอีกตัวอย่างการวาด quadratic curve ใน HTML5:
ตัวอย่าง
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height: 100px;
margin: 0px auto;
}
</style>
<script type>
function drawShape() {
var canvas = document.getElementById('mycanvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(75,25);
ctx.quadraticCurveTo(25,25,25,62.5);
ctx.quadraticCurveTo(25,100,50,100);
ctx.quadraticCurveTo(50,120,30,125);
ctx.quadraticCurveTo(60,120,65,100);
ctx.quadraticCurveTo(125,100,125,62.5);
ctx.quadraticCurveTo(125,25,75,25);
ctx.stroke();
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id="test" onload="drawShape();">
<canvas id="mycanvas"></canvas>
</body>
</html>
ผลลัพธ์
