<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <img src="http://img.zcool.cn/community/0142135541fe180000019ae9b8cf86.jpg@1280w_1l_2o_100sh.png" alt="" class="bg_img"> <img src="" alt="" id="code" class="code"> <input type="file" id="file"> <input type="text" placeholder="请输入文字" id="text"> <button>生成</button> <!--canvas--> <div class="canvas_box"></div> <!--img--> <img src="" alt="" class="canvas_box_img"> </body> </html> <script> var reader = new FileReader(); var input = document.getElementById("file"); input.onchange = function(){ var file = this.files[0]; if(!!file){ var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function(){ document.getElementById("code").src = this.result; } } } function convertImageToCanvas(image){ var canvas = document.createElement("canvas"); canvas.id='create_canvas' for(let i=0;i<2;i++){ if(i==0){ canvas.width = image[0].width; canvas.height = image[0].height; canvas.getContext("2d").drawImage(image[0],0,0); }else{ canvas.getContext("2d").drawImage(image[i],0,0,100,100); } } canvas.getContext("2d").font = '20px Arial'; canvas.getContext("2d").fillStyle = 'red'; canvas.getContext("2d").fillText(document.getElementById('text').value,100,100) return canvas; } function convertCanvasToImage(){ var canvas=document.getElementById('create_canvas') var image = new Image(); console.log(111) image.crossOrigin="anonymous"; image.src = canvas.toDataURL("image/png"); return image; } document.querySelector('button').onclick=function(){ document.querySelector('.canvas_box').appendChild(convertImageToCanvas([document.querySelector('.bg_img'),document.getElementById("code")])) } </script> <style> .bg_img{ 500px; height: 300px; object-fit: cover; } .code{ 100px; height: 100px; object-fit: cover; } .canvas_box_img{ 500px; height: 300px; object-fit: cover; } </style>