Canvas(HTML5)
<canvas id="test-canvas" width="300" height="200"></canvas>
是否支持Canvas
'use strict';
var canvas = document.getElementById('test-canvas');
if (canvas.getContext) {
alert('你的瀏覽器支持Canvas!');
} else {
alert('你的瀏覽器不支持Canvas!');
}
繪制2D
var ctx = canvas.getContext('2d');
繪制3D
gl = canvas.getContext("webgl");
繪制形狀
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
'use strict';
function doClick() {
var
canvas = document.getElementById('test-shape-canvas'),
ctx = canvas.getContext('2d');
//擦除(0,0)位置大小為200x200的矩形,擦除的意思是把該區(qū)域變透明
ctx.clearRect(0, 0, 200, 200);
ctx.fillStyle = '#dddddd';
ctx.fillRect(10, 10, 130, 130);
var path = new Path2D();
path.arc(75, 75, 50, 0, Math.PI * 2, true);
path.moveTo(110, 75);
path.arc(75, 75, 35, 0, Math.PI, false);
path.moveTo(65, 65);
path.arc(60, 65, 5, 0, Math.PI * 2, true);
path.moveTo(95, 65);
path.arc(90, 65, 5, 0, Math.PI * 2, true);
ctx.strokeStyle = '#0000ff';
ctx.stroke(path);
}
</script>
</head>
<body>
<canvas id="test-shape-canvas" width="200" height="200" style="border: 1px solid #ccc; margin-top: 15px;">
</canvas>
<input type="button" name="Button" onclick="doClick()">
</body>
</html>
繪制文字
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
'use strict';
function doClick() {
var canvas = document.getElementById('test-text-canvas'),
ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;
ctx.shadowBlur = 2;
ctx.shadowColor = '#666666';
ctx.font = '24px Arial';
ctx.fillStyle = '#333333';
ctx.fillText('帶陰影的文字', 20, 40);
}
</script>
</head>
<body>
<canvas id="test-text-canvas" width="300" height="100" style="border: 1px solid #ccc; margin-top: 15px;">
</canvas>
<input type="button" name="Button" onclick="doClick()">
</body>
</html>