หมายเหตุ : ตำแหน่งเริ่มต้นการวาด (0,0) อยู่ที่ มุมซ้ายบนของผู้อ่านครับ
ตัวอย่าง แทคที่ใช้
1 | < canvas height = "200" id = "myCanvas" width = "578" ></ canvas > |
1 2 3 4 5 6 7 | var canvas = document.getElementById( 'myCanvas' ); var context = canvas.getContext( '2d' ); context.beginPath(); context.moveTo(100, 150); // เริ่มต้น cursor (ตำแหน่งเริ่มต้นของ context) context.lineTo(450, 50); // ตำแหน่งปลายทาง context.stroke(); |
ผลลัพธ์ที่ได้คือ
จะสังเกตุว่าหากสร้างเส้นธรรมดาเส้นจะมีขนาดเล็ก เราสามารถเพิ่มขนาดของเส้นได้โดยใช้ lineWidth ของ canvas context.
1 | context.lineWidth = 15; |
ตัวอย่าง : การเพิ่มขนาดเส้น
1 2 3 4 5 6 7 8 | var canvas = document.getElementById( 'myCanvas' ); var context = canvas.getContext( '2d' ); context.beginPath(); context.moveTo(100, 150); context.lineWidth = 15; // เพิ่มขนาดเส้น context.lineTo(450, 50); context.stroke(); |
ผลลัพธ์ที่ได้คือ
ต่อไปเป็นเรื่องของสีเส้นหากเราไม่ได้กำหนดค่าใดๆไว้ โดยทั่วไปจะเป็นสีดำ เพื่อที่จะเปลี่ยนสีของเส้นเราต้องใช้ strokeStyle ของ canvas context ครับ โดยสามารถกำหนดค่าสีได้ในรูปแบบของข้อความ เช่น red, green, blue หรือจะใช้ในแบบค่า hex เช่น #FF0000 , #555, หรือจะเป็นในรูปแบบของค่า RGB ก็ได้เช่นเดียวกัน rgb(255, 0, 0).
1 2 | // set line color context.strokeStyle = '#ff0000' ; |
1 2 3 4 5 6 7 8 9 | var canvas = document.getElementById( 'myCanvas' ); var context = canvas.getContext( '2d' ); context.beginPath(); context.moveTo(100, 150); context.lineWidth = 15; context.strokeStyle = '#ff0000' ; // ใส่สีเส้น context.lineTo(450, 50); context.stroke(); |
คุณสมบัติต่อมาเป็นเรื่องของ Cap ปลายเส้น โดยเราสามารถที่จะกำหนด cap ของเส้นได้โดยใช้ lineCap โดยมีให้เลือกอยู่สามแบบคือ butt, round, และ square หากไม่ได้ระบุไว้จะมีค่าทั่วไปเป็น butt.
1 | context.lineCap = 'round' ; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | var canvas = document.getElementById( 'myCanvas' ); var context = canvas.getContext( '2d' ); // butt line cap (top line) context.beginPath(); context.moveTo(200, canvas.height / 2 - 50); context.lineTo(canvas.width - 200, canvas.height / 2 - 50); context.lineWidth = 20; context.strokeStyle = '#0000ff' ; context.lineCap = 'butt' ; // กำหนด cap แบบ butt context.stroke(); // round line cap (middle line) context.beginPath(); context.moveTo(200, canvas.height / 2); context.lineTo(canvas.width - 200, canvas.height / 2); context.lineWidth = 20; context.strokeStyle = '#0000ff' ; context.lineCap = 'round' ; // กำหนด cap แบบ round context.stroke(); // square line cap (bottom line) context.beginPath(); context.moveTo(200, canvas.height / 2 + 50); context.lineTo(canvas.width - 200, canvas.height / 2 + 50); context.lineWidth = 20; context.strokeStyle = '#0000ff' ; context.lineCap = 'square' ; // กำหนด cap แบบ square context.stroke(); |
อ้างอิง : ที่นี่
0 comments:
Post a Comment