Record --canvas basic operations

Here I will share with you some of the knowledge I have summarized on the Internet, I hope it will be helpful to everyone

1. Here are some tips about using Canvas:

  1. Drawing basic shapes: Canvas can be used to draw various basic shapes, such as rectangles, circles, lines, etc. Use fillRect()the method to draw rectangles, arc()the method to draw circles, lineTo()the method to draw lines, etc.
  2. Draw text: Use fillText()the or strokeText()method to draw text on the Canvas. Attributes such as font, size, and color can be set to customize the text style.
  3. Drawing images: Canvas can load and draw images, and use drawImage()the method to draw images on Canvas. You can set the image's position, size and other properties.
  4. Gradient and shadow: Canvas supports gradient and shadow effects. You can use createLinearGradient()the or createRadialGradient()method to create a gradient object, and use fillStylethe property to apply it to the shape. Use shadowOffsetXthe , shadowOffsetY, shadowBlurand shadowColorattributes to create shadow effects.
  5. Animation effects: Canvas can be used to create animation effects. requestAnimationFrame()Smooth animations can be achieved by updating element positions or properties on the Canvas every frame and recursively calling animation functions using the method.
  6. Saving and Restoring State: Drawing operations on the Canvas can use save()the and restore()methods to save and restore state. This is useful for switching styles, translating, rotating, etc. during drawing.

2. Basic graphics drawing methods and parameters are explained as follows:

  1. Draw the rectangle ( fillRect() ):
    • Parameters: fillRect(x, y, width, height)
    • x and y represent the coordinates of the upper left corner of the rectangle, and width and height represent the width and height of the rectangle.
  2. Draw a circle ( arc() ):
    • 参数: arc(x, y, radius, startAngle, endAngle, anticlockwise)
    • x and y represent the coordinates of the center of the circle, radius represents the radius, startAngle and endAngle represent the start angle and end angle (in radians), and anticlockwise represents whether to draw counterclockwise.
  3. Draw the line ( lineTo() ):
    • Parameters: lineTo(x, y)
    • x and y represent the coordinates of the end point of the line.
  4. Draw text ( fillText() and strokeText() ):
    • Parameters: fillText(text, x, y) or strokeText(text, x, y)
    • text represents the text to be drawn, and x and y represent the coordinates of the starting position of the text.

3. To draw text on the Canvas, you can use the fillText() or strokeText() method. The parameters and usage of these methods are as follows:

  1. fillText(text, x, y [, maxWidth]) :
  • text: The text content to be drawn.
  • x and y: the coordinates of the starting position of the text, that is, the coordinates of the lower left corner or the left center point of the text.
  • maxWidth (optional): The maximum width of the text, the text will wrap when the width is exceeded.
  1. strokeText(text, x, y [, maxWidth]) :
  • text: The text content to be drawn.
  • x and y: the coordinates of the starting position of the text, that is, the coordinates of the lower left corner or the left center point of the text.
  • maxWidth (optional): The maximum width of the text, the text will wrap when the width is exceeded.

Sample code:

	const canvas = document.getElementById('myCanvas');
	const ctx = canvas.getContext('2d');
	
	ctx.font = '24px Arial'; // 设置字体样式和大小
	ctx.fillStyle = 'black'; // 设置文本颜色
	ctx.fillText('Hello, World!', 50, 50); // 绘制填充文本
	
	ctx.strokeStyle = 'red'; // 设置描边颜色
	ctx.lineWidth = 2; // 设置描边宽度
	ctx.strokeText('Hello, World!', 50, 100); // 绘制描边文本

The above code will draw a filled text and a stroked text on the Canvas at coordinates (50, 50) and (50, 100) respectively.

Please note that properties such as font style and color need to be set before drawing text. At the same time, you can use the measureText() method to obtain the width information of the text for layout and alignment operations.

4. Use of beginPath()

beginPath() is a method in Canvas, used to start a new path. A path can be a line, a curve, a rectangle, or a closed shape.

After using beginPath(), you can use other drawing methods (such as moveTo(), lineTo(), arc(), etc.) to create the path. When you're done drawing the path, you can use the stroke() or fill() methods to stroke or fill the path.

以下是 beginPath() 方法的基本使用示例:

	const canvas = document.getElementById('myCanvas');
	const ctx = canvas.getContext('2d');
	
	ctx.beginPath(); // 开始新的路径
	
	// 绘制路径
	ctx.moveTo(50, 50); // 移动到起始点
	ctx.lineTo(100, 100); // 绘制一条直线
	ctx.arc(150, 50, 30, 0, Math.PI * 2, false); // 绘制一个圆弧
	ctx.closePath(); // 闭合路径
	
	ctx.stroke(); // 描边路径

在上述示例中,我们先调用了 beginPath() 方法开始一个新的路径,然后使用 moveTo() 、 lineTo() 和 arc() 方法绘制了一条线和一个圆弧,最后使用 closePath() 方法将路径闭合。最后,我们调用 stroke() 方法描边路径。

beginPath() 方法的作用是开始一个新的路径,清除之前定义的路径,以便绘制新的路径。这在需要绘制多个不相关的路径时非常有用,可以避免不同路径之间的重叠或干扰。

绘制矩形时,不需要使用 beginPath() 方法。 beginPath() 方法主要用于创建和定义路径,而绘制矩形可以直接使用 fillRect() 或 strokeRect() 方法进行绘制,不需要通过路径来实现。

5. 绘制图像方法和参数

在Canvas中绘制图像有多种方法,其中最常用的方法是使用 drawImage() 函数。 drawImage() 函数可以绘制图像到Canvas上,并可以根据需要调整图像的位置、大小和剪裁。 drawImage() 函数的基本语法如下: ctx.drawImage(image, x, y); 其中, image 是要绘制的图像对象,可以是 <img> 元素、 <canvas> 元素或 <video> 元素。 xy 是图像在Canvas上的坐标位置。 除了基本的 drawImage() 函数外,还可以使用其他参数来调整图像的大小和剪裁。以下是 drawImage() 函数的常用参数:

  • ctx.drawImage(image, x, y, width, height) :指定绘制图像的宽度和高度,可以将图像缩放到指定的大小。
  • ctx.drawImage(image, sx, sy, swidth, sheight, x, y, width, height) :可以剪裁图像的一部分,并在Canvas上指定位置绘制。 例如,下面的代码将在Canvas上绘制一个图像:
	const canvas = document.getElementById('myCanvas');
	const ctx = canvas.getContext('2d');
	const image = new Image();
	image.src = 'image.jpg';
	 image.onload = function() {
	  ctx.drawImage(image, 0, 0);
	}

在上述示例中,我们创建了一个 <img> 元素,并将其赋值给 image 变量。然后,使用 drawImage() 函数将图像绘制到Canvas上,坐标为(0, 0)。

6. 渐变和阴影

渐变和阴影是Canvas中常用的效果,可以通过Canvas的API来实现。

  1. 渐变(Gradient): 渐变可以用来创建平滑的过渡效果,可以是线性渐变或径向渐变。
    • 线性渐变(Linear Gradient): 使用 createLinearGradient() 方法创建线性渐变对象,指定起始点和结束点的坐标,然后使用 addColorStop() 方法指定渐变的颜色和位置。 示例代码:
	const canvas = document.getElementById('myCanvas');
	     const ctx = canvas.getContext('2d');
	      const gradient = ctx.createLinearGradient(0, 0, 200, 0);
	     gradient.addColorStop(0, 'red');
	     gradient.addColorStop(1, 'blue');
	      ctx.fillStyle = gradient;
	     ctx.fillRect(0, 0, 200, 200);
  • 径向渐变(Radial Gradient): 使用 createRadialGradient() 方法创建径向渐变对象,指定内圆和外圆的坐标和半径,然后使用 addColorStop() 方法指定渐变的颜色和位置。 示例代码:
	const canvas = document.getElementById('myCanvas');
	     const ctx = canvas.getContext('2d');
	      const gradient = ctx.createRadialGradient(100, 100, 50, 100, 100, 100);
	     gradient.addColorStop(0, 'red');
	     gradient.addColorStop(1, 'blue');
	      ctx.fillStyle = gradient;
	     ctx.fillRect(0, 0, 200, 200);
  • 阴影(Shadow): 阴影效果可以通过设置Canvas的阴影属性来实现。使用 shadowColor 指定阴影的颜色, shadowOffsetXshadowOffsetY 指定阴影的偏移量, shadowBlur 指定阴影的模糊程度。 示例代码:
const canvas = document.getElementById('myCanvas');
   const ctx = canvas.getContext('2d');
    ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
   ctx.shadowOffsetX = 5;
   ctx.shadowOffsetY = 5;
   ctx.shadowBlur = 10;
    ctx.fillStyle = 'red';
   ctx.fillRect(50, 50, 100, 100);

7. 动画效果

动画效果在Canvas中可以通过多种方式实现,以下是几种常见的动画效果:

  1. 基于帧的动画(Frame-based Animation): 基于帧的动画是通过在Canvas上连续绘制不同的帧来创建动画效果。可以使用 requestAnimationFrame() 方法来实现帧动画,该方法会在浏览器每次重新绘制页面时调用指定的回调函数。 示例代码:
	const canvas = document.getElementById('myCanvas');
	   const ctx = canvas.getContext('2d');
	   let x = 0;
	    function animate() {
	     ctx.clearRect(0, 0, canvas.width, canvas.height);
	     ctx.fillRect(x, 50, 50, 50);
	     x += 1;
	     if (x > canvas.width) {
	       x = 0;
	     }
	     requestAnimationFrame(animate);
	   }
	    animate();
在上述示例中,我们使用 requestAnimationFrame() 方法循环调用 animate() 函数,每次调用时清除Canvas并绘制一个矩形,并将矩形的x坐标递增,实现了一个矩形在Canvas上移动的动画效果。 2. 通过改变属性值的动画(Property-based Animation): 除了基于帧的动画外,还可以通过改变属性值来实现动画效果。可以使用 setInterval()setTimeout() 方法来定时改变属性值,并在每次改变后重新绘制Canvas,从而创建动画效果。 示例代码:
	const canvas = document.getElementById('myCanvas');
	   const ctx = canvas.getContext('2d');
	   let x = 0;
	    function animate() {
	     ctx.clearRect(0, 0, canvas.width, canvas.height);
	     ctx.fillRect(x, 50, 50, 50);
	     x += 1;
	     if (x > canvas.width) {
	       clearInterval(animation);
	     }
	   }
	    const animation = setInterval(animate, 10);
在上述示例中,我们使用 setInterval() 方法每隔一段时间调用一次 animate() 函数,每次调用时清除Canvas并绘制一个矩形,并将矩形的x坐标递增,直到达到指定的条件后清除定时器,停止动画效果。 3. 使用第三方库: 除了原生的Canvas API外,还可以使用一些第三方库来简化动画效果的创建,如GreenSock Animation Platform (GSAP)、Anime.js等。这些库提供了更多的动画效果和控制选项,可以帮助开发者更方便地创建复杂的动画效果。

本文转载于:

https://juejin.cn/post/7259558728059158588

如果对您有所帮助,欢迎您点个关注,我会定时更新技术文档,大家一起讨论学习,一起进步。

 

Guess you like

Origin blog.csdn.net/qq_40716795/article/details/131951402