ผ้าใบ HTML drawImage ()วิธี การ
ภาพที่จะใช้:
ตัวอย่าง
วาดภาพลงบนผืนผ้าใบ:
จาวาสคริปต์:
window.onload = function() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 10, 10);
};
รองรับเบราว์เซอร์
ตัวเลขในตารางระบุเบราว์เซอร์รุ่นแรกที่รองรับวิธีการนี้อย่างเต็มที่
Method | |||||
---|---|---|---|---|---|
drawImage() | Yes | 9.0 | Yes | Yes | Yes |
ความหมายและการใช้งาน
วิธี drawImage() วาดภาพ แคนวาส หรือวิดีโอลงบนผืนผ้าใบ
วิธี drawImage() ยังสามารถวาดส่วนต่างๆ ของรูปภาพ และ/หรือเพิ่ม/ลดขนาดรูปภาพได้
หมายเหตุ:คุณไม่สามารถเรียกเมธอด drawImage() ก่อนที่ภาพจะโหลด เพื่อให้แน่ใจว่าโหลดรูปภาพแล้ว คุณสามารถเรียก drawImage() จาก window.onload() หรือจาก document.getElementById(" imageID ").onload
JavaScript Syntax
วางตำแหน่งรูปภาพบนผืนผ้าใบ:
JavaScript syntax: | context.drawImage(img,x,y); |
---|
วางตำแหน่งรูปภาพบนผืนผ้าใบ และระบุความกว้างและความสูงของรูปภาพ:
JavaScript syntax: | context.drawImage(img,x,y,width,height); |
---|
คลิปรูปภาพและวางตำแหน่งส่วนที่ตัดไว้บนผืนผ้าใบ:
JavaScript syntax: | context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height); |
---|
ค่าพารามิเตอร์
Parameter | Description | Play it |
---|---|---|
img | Specifies the image, canvas, or video element to use | |
sx | Optional. The x coordinate where to start clipping | |
sy | Optional. The y coordinate where to start clipping | |
swidth | Optional. The width of the clipped image | |
sheight | Optional. The height of the clipped image | |
x | The x coordinate where to place the image on the canvas | |
y | The y coordinate where to place the image on the canvas | |
width | Optional. The width of the image to use (stretch or reduce the image) | |
height | Optional. The height of the image to use (stretch or reduce the image) |
ตัวอย่างเพิ่มเติม
ตัวอย่าง
วางตำแหน่งรูปภาพบนผืนผ้าใบ และระบุความกว้างและความสูงของรูปภาพ:
จาวาสคริปต์:
window.onload = function() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 10, 10, 150, 180);
};
ตัวอย่าง
คลิปรูปภาพและวางตำแหน่งส่วนที่ตัดไว้บนผืนผ้าใบ:
จาวาสคริปต์:
window.onload = function() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 90, 130, 50, 60, 10, 10, 50, 60);
};
ตัวอย่าง
วิดีโอที่จะใช้ (กดเล่นเพื่อเริ่มการสาธิต):
ผ้าใบ:
JavaScript (โค้ดจะดึงเฟรมปัจจุบันของวิดีโอทุกๆ 20 มิลลิวินาที):
var v = document.getElementById("video1");
var c = document.getElementById("myCanvas");
var ctx = c.getContext('2d');
var i;
v.addEventListener('play',function() {i=window.setInterval(function()
{ctx.drawImage(v,5,5,260,125)},20);},false);
v.addEventListener('pause',function() {window.clearInterval(i);},false);
v.addEventListener('ended',function() {clearInterval(i);},false);
❮ อ้างอิงผ้าใบ HTML