
canvas
base
使用 元素时,您可以通过获取其上下文(context)并使用上下文提供的方法来绘制图形,文字,和图像。以下是 元素的一些基础用法:
获取上下文(context):首先,您需要通过调用 `` 元素的 getContext() 方法来获取绘图上下文。这个方法接收一个参数,表示上下文类型。对于二维图形绘制,使用 “2d” 参数。
1 2 3
| const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d");
|
绘制形状:您可以使用上下文提供的方法绘制各种形状,如矩形、圆形、线条等。
1 2 3 4 5 6 7 8 9 10 11
| ctx.fillRect(x, y, width, height);
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke();
|
填充和描边样式:您可以使用上下文的 fillStyle 和 strokeStyle 属性来定义填充和描边的颜色或样式。
1 2 3 4 5 6 7
| ctx.fillStyle = "red"; ctx.fillRect(x, y, width, height);
ctx.strokeStyle = "#00ff00"; ctx.lineWidth = 2; ctx.strokeRect(x, y, width, height);
|
绘制文本:您可以使用上下文的 fillText() 或 strokeText() 方法绘制文本。
1 2 3 4
| ctx.font = "20px Arial"; ctx.fillStyle = "black"; ctx.fillText("Hello, World!", x, y);
|
加载并绘制图像:您可以使用上下文的 drawImage() 方法加载和绘制图像。
1 2 3 4 5 6
| const image = new Image(); image.src = "image.png";
image.onload = function() { ctx.drawImage(image, x, y); };
|
绘制视频
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| const video = document.createElement("video"); video.src = "video.mp4";
const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d");
video.addEventListener("loadeddata", function() { canvas.width = video.videoWidth; canvas.height = video.videoHeight;
function drawFrame() { ctx.drawImage(video, 0, 0, canvas.width, canvas.height); requestAnimationFrame(drawFrame); }
video.play(); drawFrame(); });
document.body.appendChild(canvas);
|