xb18
xb18
文章78
标签0
分类0
canvas

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();

填充和描边样式:您可以使用上下文的 fillStylestrokeStyle 属性来定义填充和描边的颜色或样式。

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);
本文作者:xb18
本文链接:https://moelj.com/2024/03/26/canvas/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可