HTML5 Canvas
HTML5 Canvas
在 HTML5 中,引入了一个全新的元素:canvas。Canvas 允许通过 JavaScript 来绘制图形。
基本语法
<canvas id="myCanvas" width="600" height="400"></canvas>
其中 id
属性定义 canvas 的唯一标识符,width
和 height
属性指定了 canvas 的宽度和高度。
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
<canvas>
元素本身只是一个图形容器,必须使用 JavaScript 来绘制图形。getContext()
方法返回一个对象,该对象拥有绘画方法和属性。
绘制图形
线条
// 定义起点
ctx.moveTo(0, 0);
// 定义终点
ctx.lineTo(200, 100);
// 绘制线条
ctx.stroke();
文字
ctx.font = "30px Arial";
ctx.fillText("Hello World", 10, 50);
矩形
// 绘制填充矩形
ctx.fillRect(10, 10, 100, 50);
// 绘制边框矩形
ctx.strokeRect(10, 10, 100, 50);
// 擦除矩形范围内的像素
ctx.clearRect(10, 10, 100, 50);
圆形
// 绘制填充圆形
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2*Math.PI);
ctx.fill();
// 绘制边框圆形
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2*Math.PI);
ctx.stroke();
图像
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
img.src = "image.jpg";
设置样式
线条样式
// 设置线条颜色
ctx.strokeStyle = "red";
// 设置线条宽度
ctx.lineWidth = 5;
// 设置线条末端样式
ctx.lineCap = "round";
// 设置线条连接样式
ctx.lineJoin = "round";
// 绘制线条
ctx.stroke();
填充样式
// 设置填充颜色
ctx.fillStyle = "blue";
// 绘制填充矩形
ctx.fillRect(10, 10, 100, 50);
文字样式
// 设置字体样式
ctx.font = "30px Arial";
// 设置文字颜色
ctx.fillStyle = "red";
// 绘制文字
ctx.fillText("Hello World", 10, 50);