ในการวาดผืนผ้าใบบนเว็บเพจ ให้ใช้องค์ประกอบผ้าใบ HTML5
ผ้าใบทุกผืนมีองค์ประกอบสองอย่างที่อธิบายความสูงและความกว้างของผืนผ้าใบ นั่นคือ ความสูงและความกว้างตามลำดับ
ด้วยเหตุนี้ คุณยังต้องตั้งค่า id สำหรับ canvas ตามที่แสดงในข้อมูลโค้ดด้านล่าง -
<canvas id = "newCanvas" width = "100" height = "100"></canvas>
ค้นหาองค์ประกอบ
var canvas = document.getElementById("newCanvas"); ในการแสดงบางสิ่งบนแคนวาส อันดับแรก สคริปต์ต้องเข้าถึงบริบทการแสดงผลและวาดลงบนมัน
ให้เราดูตัวอย่างการวาดเส้นทางใน HTML5 ด้วย
ตัวอย่าง
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
background-color: orange;
}
</style>
<script>
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// Draw shapes
ctx.beginPath();
ctx.arc(75,75,50,0,Math.PI*2,true); // Outer circle
ctx.moveTo(110,75);
ctx.arc(75,75,35,0,Math.PI,false); // Mouth
ctx.moveTo(65,65);
ctx.arc(60,65,5,0,Math.PI*2,true); // Left eye
ctx.moveTo(95,65);
ctx.arc(90,65,5,0,Math.PI*2,true); // Right eye
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> ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

เรามาดูตัวอย่างการวาดเส้นโค้งกำลังสองใน HTML5 กัน −
ตัวอย่าง
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type>
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// Draw shapes
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> ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
