SoFunction
Updated on 2025-04-10

Example of js implementing mutual conversion between canvas pictures and img pictures

Recently, I encountered a problem in a project where I needed to convert the generated QR code in the form of canvas into a picture, and I could long press to identify, save, etc. I found some information and summarized some knowledge.

By default, it is performed in the jq library, and the library is introduced, and the canvas image is converted into img image. The code is as follows.

<body>
  <div ></div>
  <div ></div>
</body>
<script>
//Generate QR code in the form of canvas$("#cans").qrcode({
  width:150,
  height:150,
  text:'/dxzg/p/'//The content that needs to be generated  });
  
//Extract image from canvas imagefunction convertCanvasToImage(canvas) { 
  //The new Image object can be understood as DOM  var image = new Image(); 
  // Returns a string of Base64 encoded URLs  // Specify format PNG   = ("image/png"); 
  return image; 
} 

//Get the canvas object in the web pagevar mycans=$('canvas')[0];  
//Calling convertCanvasToImage function to convert canvas into img formvar img=convertCanvasToImage(mycans); 
//Insert img into the container$('#img').append(img); 
</script>

Similarly, you can also convert the image to canvas, and the conversion function is as follows:

// Convert image to canvas objectfunction convertImageToCanvas(image) { 
  // Create a canvas DOM element and set its width and height the same as the picture  var canvas = ("canvas"); 
   = ; 
   = ; 
  // Coordinates (0,0) indicate the drawing from here, which is equivalent to offset.  ("2d").drawImage(image, 0, 0);  
  return canvas; 
} 

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.