You can get the canvas content in the web page like this and save it locally in the form of an image.


In JavaScript, we can obtain the canvas content in the browser page through the following steps, convert it into an image and save it locally


1. Get the canvas element. We can use JavaScript's document.getElementById() or document.querySelector() method to get the canvas element.

2. Get the drawing context of canvas. We can use the canvas.getContext() method to obtain the drawing context of canvas.

3. Use the toDataURL() method to convert the canvas content to the base64 encoding of the image. This method accepts a parameter to specify the format of the output image. For example, toDataURL('image/png') will output image data in PNG format.

4. Create an img element and set its src attribute to the base64 encoding obtained in step 3.

5. Create an a element and set its href attribute to the base64 encoding obtained in step 3. Also, set its download attribute to the desired image file name.

6. Add the a element to the DOM and simulate clicking on the a element to trigger file download.

The code is as follows (example):

	// 获取canvas元素
	var canvas = document.getElementById('myCanvas');
	
	// 获取canvas的绘图上下文
	var ctx = canvas.getContext('2d');
	
	// 绘制内容
	//ctx.fillRect(0, 0, 100, 100);
	
	// 将canvas内容转换为图片的base64编码
	var dataURL = canvas.toDataURL('image/png');
	
	// 创建img元素,用于预览图片
	var img = document.createElement('img');
	img.src = dataURL;
	document.body.appendChild(img);
	
	// 创建a元素,用于下载图片
	var link = document.createElement('a');
	link.href = dataURL;
	link.download = 'myImage.png';
	
	// 添加a元素到DOM中,并触发点击事件以下载图片
	document.body.appendChild(link);
	link.click();


Summarize

The above code converts the rectangle drawn by the canvas into a picture in PNG format, and saves it in the variable dataURL in the form of base64 encoding. The code then creates an img element for previewing the image, and an a element for downloading the image. Finally, the code adds the a element to the DOM and triggers its click event to download the image locally.

Guess you like

Origin blog.csdn.net/weixin_44072916/article/details/129425110