Home >Web Front-end >HTML Tutorial >How to convert html to images
When we make h5 pages or promote small programs, especially in WeChat, in order to allow users to better share with friends, we often need to generate an image from the dynamically generated HTML, and then let the user press and hold to save and send it to Friends or circle of friends.
1. Create a new canvas in HTML
/**要生成图片的html*/<p class="con_1"> <p class="con_1_5"> <span class="title_des2">思路惊奇</span> <span class="title_des3">思路惊奇</span> </p> <img class="con_1_1" src="style/ActiveCDN/bonus/page7_1.png" alt=""> <img class="con_1_2" src="style/ActiveCDN/bonus/page7_1.png" alt=""> </p>/*生成的canvas和最终生成的图片*/<p class="shareImg"> <canvas id="canvas" width="750" height="1206"></canvas> <img src="" alt=""> </p>
//设置canva画布大小,这里会把画布大小设置为2倍,为了解决生成图片不清晰的问题,需要注意接下来所有的函数都是在html2canvas这个对象里定义的 var html2canvas={ canvas:document.getElementById("canvas"), ctx:canvas.getContext("2d"), saveImage:function(){ this.canvas.width=windowPro.innerWidth*2; this.canvas.height=windowPro.innerHeight*2-4.8*bastFontSize; this.ctx.fillStyle="#0c3e78"; this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height); } }
2. Load the DOM element of the image to be generated into the canvas
a, Get the image to be loaded into the canvas
domArray:[$(".con_1_1"),$(".con_1_2")],//要加载的图片元素列表 imgArrayLoad:function(){ var that=this,domArray=this.domArray; for(var i=0,len=domArray.length;i<len;i++){ (function(){ //循环出所有图片元素,一个个图片添加 that.addImgToCanvas(domArray[i],that.imgAllLoad); }()) } },
b, Get the size of each image element on the page, the distance from the top, and then draw it to the corresponding position on the canvas
addImgToCanvas:function(obj,fn){ var width=obj.width()*2,//图片在网页宽度
height=obj.height()*2,//图片在网页高度
x=obj[0].x*2,//图片距离网页最顶部距离
y=obj[0].y*2,//图片距离网页最右边距离
img=new Image(),
that=this,
src=obj.attr("src");
img.src=src;
img.onload=function(){ //把图片绘制到canvas上
that.ctx.drawImage(obj[0],x,y,width,height);上
that.loadImgNum++; if(fn && typeof fn === "function")fn(that.loadImgNum); /**位置1**/
}
},
3, load the DOM element of the text to be generated into the canvas
a, get the text element to be loaded
textObj:[$(".title_des2"),$(".title_des3")], textArratLoad:function(){ var that=this; for(var m=0,len=that.textObj.length;m<len;m++){ (function(){ that.writeTextOnCanvas(domArray[m],parseInt(28)+"px 微软雅黑","#d0b150") })() } },
b, get the distance between each text element and the web page. Similarly, the distance length must be doubled. Add the text to the canvas
writeTextOnCanvas:function(obj,fontsize,color){//添加文字到canvas var width=obj.width()*2, height=obj.height()*2, x=obj.offset().left*2, y=obj.offset().top*2; var that=this; var text=obj.html().replace(/^\s+|\s+$/, "");//去掉文字里的空格 that.ctx.fillStyle =color; //设置文字颜色 that.ctx.font = fontsize;//设置文字大小 that.ctx.textAlign="left";//设置文字对其方向 textBaseline = "middle"; //因为canvas里的文字不会换行,所以我们需要想办法让长段文字换行 for(var i = 1; that.getTrueLength(text) > 0; i++){ var tl = that.cutString(text, 30); that.ctx.fillText(text.substr(0, tl), x, y+36*i);// 把文字添加到canvas上 text = text.substr(tl); } },
c. When the text is drawn to the canvas, it will automatically wrap. . Because when drawing text on canvas, you can only set the maximum width and distance from the top and left. So we need to handle it ourselves.
getTrueLength:function(str){//获取字符串的真实长度(字节长度) var len = str.length, truelen = 0; for(var x = 0; x < len; x++){ if(str.charCodeAt(x) > 128){ truelen += 2; }else{ truelen += 1; } } return truelen; }, cutString:function(str, leng){//按字节长度截取字符串,返回substr截取位置 var len = str.length, tlen = len, nlen = 0; for(var x = 0; x < len; x++){ if(str.charCodeAt(x) > 128){ if(nlen + 2 < leng){ nlen += 2; }else{ tlen = x; break; } }else{ if(nlen + 1 < leng){ nlen += 1; }else{ tlen = x; break; } } } return tlen; }
4. Finally, convert the canvas into a picture. It should be noted that you must wait until all pictures are loaded before the picture can be generated, otherwise the generated picture will be incomplete. Text loading can be ignored.
imgAllLoad:function(nexi){ var length=this.domArray.length; if(nexi>=length){ var dataURL = canvas.toDataURL(); $(".shareImg img").attr("src",dataURL);//canvas转为图片 } }
Summary:
1. Get the image and text positions and draw them through ctx.drawImage(IMG,left,top,width,height) of canvas For pictures, draw text through .ctx.fillText(text, left,top), and generate pictures through canvas.toDataURL();.
2. It should be noted that in order to generate images without distortion, the canvas size is 2 times, and the image text is 2 times.
3. To wrap text, getTrueLength.
4. You must wait until the pictures are drawn before generating the pictures. This is very important.
Related recommendations:
html5 - html image click event not found
javascript - html image hot Areas such as adaptive map tags
The above is the detailed content of How to convert html to images. For more information, please follow other related articles on the PHP Chinese website!