Home  >  Article  >  Web Front-end  >  Create canvas using html to generate pictures

Create canvas using html to generate pictures

墨辰丷
墨辰丷Original
2018-05-16 09:26:574105browse

This article mainly introduces how to use html to create canvas to generate pictures. Friends who are interested can refer to it. I hope it will be helpful to everyone.

1, create a new canvas 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,

Generally we want to generate the image At this time, DOM elements are basically composed of pictures and text. Some effects and the like are not suitable for generating pictures.
a, Get the image to be loaded into 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, and the distance## from the top #, and then draw it to the corresponding position on the canvas
The size and distance of the image here are also doubled, because the generated image is not clear.

  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 canvas.
is similar to inserting a picture into canvas. You need to obtain it first. Text elements determine the position of the text in the top, bottom, left, and right of the web page, and then insert it into the corresponding 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 of each text element from 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.

Solution: Specify the number of words we want to display in each line, and then intercept the corresponding length according to the length of the string. Since the number of occupied characters is inconsistent at noon, it is recommended to convert them to byte length. The method is as follows.

 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 position, draw the image through ctx.drawImage(IMG,left,top,width,height) of canvas, through .ctx. fillText(text, left,top) draws text and generates images 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. In order to wrap the text, getTrueLength
4. You must wait until the pictures are drawn before generating the pictures. This is very important.

Related recommendations:

How to use the img tag of HTML images

##HTML images and hyperlinks study notes

#Solution to the ugly blue border produced by adding a hyperlink to the html image img

The above is the detailed content of Create canvas using html to generate pictures. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:HTML basicsNext article:HTML basics