| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/zh-TW/docs/Web/API/Canvas_API/Tutorial/Basic_usage | [Back] [Original] |
Get to know MDN better
Let's start this tutorial by looking at the <canvas> HTML element itself. At the end of this page, you will know how to set up a canvas 2D context and have drawn a first example in your browser.
<canvas> <canvas id="tutorial" width="150" height="150"></canvas>
<canvas> <img> <canvas> src alt <canvas> width height DOM width height 300 pixels 150 pixels CSS
<canvas> width height CSS
HTML id <canvas><canvas> id
(margin)(border)(background)<canvas> canvas <canvas>
( IE9 IE){<canvas>}
<canvas><canvas><canvas><canvas><canvas><canvas>
canvas canvas :
<canvas id="stockGraph" width="150" height="150">
current stock price: $3.15 +0.15
</canvas>
<canvas id="clock" width="150" height="150">
<img src="images/clock.png" width="150" height="150" alt="" />
</canvas>
Apple Safari Safari 2.0 canvas CSS Safari
<canvas id="foo" ...></canvas>
<canvas>(rendering context)(rendering context)(context)WebGLOpenGL ES 3D (context) 2D (rendering context)
canvas <canvas> getContext()functiongetContext() 2D 2d
var canvas = document.getElementById("tutorial");
var ctx = canvas.getContext("2d");
document.getElementById()<canvas> getContext()
<canvas>. getContext()<canvas>:
var canvas = document.getElementById("tutorial");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
// drawing code here
} else {
// canvas-unsupported code here
}
<html>
<head>
<title>Canvas tutorial</title>
<script type="text/javascript">
function draw() {
var canvas = document.getElementById("tutorial");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
}
}
</script>
<style type="text/css">
canvas {
border: 1px solid black;
}
</style>
</head>
<body >
<canvas id="tutorial" width="150" height="150"></canvas>
</body>
</html>
draw() document load draw() window.setTimeout()setInterval()
:
alpha
<!doctype html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title>Canvas experiment</title>
</head>
<body>
<canvas id="canvas" width="150" height="150"></canvas>
<script type="application/javascript">
function draw() {
const canvas = document.getElementById("canvas");
if (canvas.getContext) {
const ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200 0 0)";
ctx.fillRect(10, 10, 50, 50);
ctx.fillStyle = "rgb(0 0 200 / 50%)";
ctx.fillRect(30, 30, 50, 50);
}
}
draw();
</script>
</body>
</html>
:
This page was last modified on 2025125 by MDN contributors.
Your blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |