API Canvas

Elemen <canvas> menentukan kawasan bitmap di halaman HTML.

API Canvas memungkinkan JavaScript untuk menggambar grafik di atas kertas.

API Canvas boleh menggambar bentuk, baris, kurva, kotak, teks dan imej, serta warna, putar, kecerahan dan lain-lain operasi pixel.

Tambahkan Canvas ke HTML

Anda boleh tambah elemen canvas di mana-mana di halaman HTML menggunakan tag <canvas>:

Contoh

<canvas id="myCanvas" width="300" height="150"></canvas>

Coba sendiri

Bagaimana untuk melawati elemen Canvas

Anda boleh guna kaedah HTML DOM getElementById() untuk melawati elemen <canvas>:

const myCanvas = document.getElementById("myCanvas");

Untuk menggambar di atas kertas, Anda perlu membuat objek konteks 2D:

const ctx = myCanvas.getContext("2d");

Catatan

Elemen HTML <canvas> sendiri tidak memiliki fungsi gambar.

Anda harus menggunakan JavaScript untuk menggambar grafik apapun.

Metode getContext() mengembalikan objek yang memiliki alat gambar (metode).

Menggambar di atas kertas

Setelah membuat objek konteks 2D, Anda dapat menggambar di atas kertas.

Metode fillRect() di bawah ini menggambar segi empat hitam, titik atas kirinya berada di posisi 20,20. Segi empat ini lebar 150 piksel dan tinggi 100 piksel:

Contoh

const myCanvas = document.getElementById("myCanvas");
const ctx = myCanvas.getContext("2d");
ctx.fillRect(20, 20, 150, 100);

Coba sendiri

Dengan warna

Properti fillStyle menetapkan warna pengisi objek gambar.

Contoh

const myCanvas = document.getElementById("myCanvas");
const ctx = myCanvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 150, 100);

Coba sendiri

Anda juga dapat menggunakan metode document.createElement() untuk membuat elemen <canvas> baru dan menambahkannya ke halaman HTML yang ada:

Contoh

const myCanvas = document.createElement("canvas");
document.body.appendChild(myCanvas);
const ctx = myCanvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 150, 100);

Coba sendiri

Path

Cara biasa untuk menggambar di atas kertas adalah:

  1. Mulai jalur - beginPath()
  2. Pindah ke titik - moveTo()
  3. Gambar di jalur - lineTo()
  4. Gambar jalur - stroke()

Contoh

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(20, 100);
ctx.lineTo(70, 100);
ctx.stroke();

Coba sendiri

Warna, gaya, dan bayangan

Atribut Description
fillStyle Tetapkan atau kembalikan warna, gradient, atau corak digunakan untuk pengisi.
strokeStyle Tetapkan atau kembalikan warna, gradient, atau corak digunakan untuk garis.
shadowColor Tetapkan atau kembalikan warna digunakan untuk bayangan.
shadowBlur Tetapkan atau kembalikan tahap kabur bayangan.
shadowOffsetX Set or return the horizontal distance of the shadow to the shape.
shadowOffsetY Set or return the vertical distance of the shadow to the shape.
Method Description
createLinearGradient() Create a linear gradient (for canvas content).
createPattern() Repeat the specified element in the specified direction.
createRadialGradient() Create a radial/circular gradient (for canvas content).
addColorStop() Specify the color and stop position in the gradient object.

Line style

Atribut Description
lineCap Set or return the line cap style.
lineJoin Set or return the type of angle created when two lines intersect.
lineWidth Set or return the current line width.
miterLimit Set or return the maximum miter length.

Rectangle

Method Description
rect() Create a rectangle.
fillRect() Draw a 'filled' rectangle.
strokeRect() Draw a rectangle (no fill).
clearRect() Clear the specified pixels within the given rectangle.

Path

Method Description
fill() Fill the current graphic (path).
stroke() Actually draw the path you define.
beginPath() Start the path or reset the current path.
moveTo() Move the path to the specified point on the canvas without creating a line.
closePath() Create a path from the current point back to the starting point.
lineTo() Add a new point and create a line from that point to the last specified point on the canvas.
clip() Cut out any shape and size of the area from the original canvas.
quadraticCurveTo() Create a quadratic Bezier curve.
bezierCurveTo() Create a cubic Bezier curve.
arc() Create an arc/curve (used to create a circle or part of a circle).
arcTo() Create an arc/curve between two tangents.
isPointInPath() Returns true if the specified point is in the current path, otherwise returns false.

Transformation

Method Description
scale() Magnify or shrink the current graphic.
rotate() Rotate the current graphic.
translate() Remap the (0,0) position on the canvas.
transform() Replace the current drawing transformation matrix.
setTransform() Reset the current transformation to the unit matrix. Then run transform()

Text

Atribut Description
font Set or return the current font attribute of the text content.
textAlign Set or return the current alignment style of the text content.
textBaseline Tetapkan atau kembalikan garis dasar teks yang digunakan untuk menggambar teks.
Method Description
fillText() Menggambar teks 'diisi' di atas kanvas.
strokeText() Menggambar teks di atas kanvas (tanpa pencahayaan).
measureText() Kembalikan objek yang mengandungi lebar teks yang ditentukan.

Pengeresan imej

Method Description
drawImage() Menggambar imej, kanvas atau video di atas kanvas.

Operasi pixel

Atribut Description
width Kembalikan lebar objek ImageData.
height Kembalikan ketinggian objek ImageData.
data Kembalikan objek yang mengandungi data imej objek ImageData yang ditentukan.
Method Description
createImageData() Cipta objek ImageData kosong baru.
getImageData() Kembalikan objek ImageData yang menyalin data pixel persegi panjang yang ditentukan di atas kanvas.
putImageData() Balikkan data imej (dari objek ImageData yang ditentukan) ke atas kanvas.

Penyusunan

Atribut Description
globalAlpha Tetapkan atau kembalikan nilai alpha atau kecerahan kenderaan pengeresan.
globalCompositeOperation Tetapkan atau kembalikan cara menggambar imej baru ke atas imej yang sedia ada.

Lain-lain

Method Description
save() Simpan keadaan konteks semasa.
restore() Kembalikan keadaan dan atribut laluan sebelum disimpan.
createEvent()
getContext()
toDataURL()

Atribut standar dan peristiwa

Objek canvas sekaligus mendukung standarAtributdanPeristiwa

Laman berkaitan

Tutorial HTML:Canvas HTML5

Tutorial Gambar HTML:教程 Canvas HTML

Panduan HTML:标签 <canvas> HTML