<canvas id="tutorial" width="300" height="300"></canvas>
<canvas>
你的瀏覽器不支持 canvas,請升級你的瀏覽器。
</canvas>
<canvas>
<img decoding="async" src="./美女.jpg" alt="">
</canvas>
我們重點(diǎn)研究 2D 渲染上下文。 其他的上下文我們暫不研究,比如, WebGL 使用了基于 OpenGL ES的3D 上下文 ("experimental-webgl") 。
var canvas = document.getElementById('tutorial');
//獲得 2d 上下文對象
var ctx = canvas.getContext('2d');
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>
<style type="text/css">
canvas {
border: 1px solid black;
}
</style>
</head>
<canvas id="tutorial" width="300" height="300"></canvas>
</body>
<script type="text/javascript">
function draw(){
var canvas = document.getElementById('tutorial');
if(!canvas.getContext) return;
var ctx = canvas.getContext("2d");
//開始代碼
}
draw();
</script>
</html>
<html>
<head>
<title>Canvas tutorial</title>
<style type="text/css">
canvas {
border: 1px solid black;
}
</style>
</head>
<canvas id="tutorial" width="300" height="300"></canvas>
</body>
<script type="text/javascript">
function draw(){
var canvas = document.getElementById('tutorial');
if(!canvas.getContext) return;
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
//繪制矩形
ctx.fillRect (10, 10, 55, 50);
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (30, 30, 55, 50);
}
draw();
</script>
</html>