1、什么是 Canvas?
HTML5 的 canvas 元素使用 JavaScript 在网页上绘制图像。
画布是一个矩形区域,您可以控制其每一像素。
canvas 拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法。
创建 Canvas 元素
<canvas id="myCanvas" width="200" height="100"></canvas>
通过 JavaScript 来绘制
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
cxt.fillStyle="#FF0000";
cxt.fillRect(0,0,150,75);
</script>
1.JavaScript 使用 id 来寻找 canvas 元素:
var c=document.getElementById("myCanvas");
2.创建 context 对象:
var cxt=c.getContext("2d");
demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas id="root" width="300" height="200" style="border: 1px solid black;"></canvas>
<script>
<!-- 获取canvas元素和绘图上下文-->
const canvas = document.getElementById('root')
const ctx = canvas.getContext('2d')
// 设置绘制样式
const fontSize = 40
ctx.font = `${fontSize}px Arial`
ctx.fillStyle = 'black'
// 要绘制的文字
const text = 'hello world'
const textWidth = ctx.measureText(text).width
const x = (canvas.width - textWidth) /2
const y = canvas.height /2
let currentTextLength = 0
let speed = 100
function drawText() {
if(currentTextLength <= text.length){
ctx.clearRect(0,0,canvas.width , canvas.height)
const currentText = text.slice(0,currentTextLength)
ctx.fillText(currentText,x,y)
currentTextLength++
requestAnimationFrame(drawText)
}
}
drawText()
</script>
</body>
</html>
demo2:
<!DOCTYPE html>
<html>
<head>
<title>Canvas Drawing Board</title>
</head>
<body>
<canvas id="drawingCanvas" width="800" height="400" style="border: 1px solid black;"></canvas>
<script>
// 获取Canvas元素和绘图上下文
const canvas = document.getElementById('drawingCanvas');
const ctx = canvas.getContext('2d');
// 设置绘制样式
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
// 记录鼠标是否按下的状态
let isDrawing = false;
// 记录鼠标位置
let lastX = 0;
let lastY = 0;
// 监听鼠标按下事件
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
});
// 监听鼠标移动事件
canvas.addEventListener('mousemove', (e) => {
if (isDrawing) {
const currentX = e.offsetX;
const currentY = e.offsetY;
drawLine(lastX, lastY, currentX, currentY);
[lastX, lastY] = [currentX, currentY];
}
});
// 监听鼠标松开事件
canvas.addEventListener('mouseup', () => {
isDrawing = false;
});
// 监听鼠标离开Canvas事件
canvas.addEventListener('mouseout', () => {
isDrawing = false;
});
function drawLine(x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
</script>
</body>
</html>