1. ホーム
  2. Web制作
  3. html5

キャンバスで簡単なポスターを描くお手本

2022-02-01 19:09:58

この製品は、ユーザーが私たちのアプリ内でWeChatやQQなどに画像を共有することを望んでいます。画像には、ユーザーの名前、アバター、およびユーザーの情報が記載されたQRコードが含まれています。製品はこのポスターを生成することができるようになります。
まず、うちのボスがhtml2canvasというプラグインがあると教えてくれたのですが、その役割はdomノードを画像に変換することです。実験してみたらうまくいったのですが、このプラグインはちょっと大きくて、投稿者のニーズに応えるためにこんな大きなものを導入するのは損した気分です なので、自分で描いた方が良いですよ〜。

まずはレンダリングから

ダンダンダンダン~~~最終的に生成されたポスターにはアバターと名前とQRコードが含まれています、もちろん写真のQRコードはBaiduのQRコードです~最終的に生成されたbase64は主要なプラットフォームに共有することができます。

さっそくですが、コードは以下の通りです(このコードは怠け者のため整理されていません。)

<canvas id="myCanvas" width="750" height="1200" style="border:1px solid #d3d3d3;background:#ffffff ;"></canvas>

domノードは単純で、canvasタグを生成して、ランダムなプロパティを書くだけです〜。

var canvas = document.getElementById("myCanvas"); //get the canvas node
function imageToCanvas(canvas,url1,url2,code) { //pass in the canvas node background image url1 avatar url2 QR code
    var ctx = canvas.getContext("2d");  
    var img1 = new Image();                               
    img1.src = url1; // the front is not explained, generate a picture
    img1.onload = function(){ 
        ctx.drawImage(img1,0,0); //when the image is loaded, assign it to the canvas, starting from 0 0.
        var img2 = new Image();
         img2.src = url2;
         img2.onload = function(){
          ctx.save(); //Save the current canvas state
          ctx.arc(374, 134, 44, 0, 2 * Math.PI); // cut the square avatar into a circle
          // Crop the circle from the canvas
          ctx.clip(); // to perform the crop
          ctx.drawImage(img2, 330, 90, 88, 88); // put img2 at 330 90 coordinates size 88
          ctx.restore(); //release the canvas state
          ctx.font="28px Arial";
          ctx.textAlign="center";
          ctx.fillStyle ='#FFFFFF'; // the front is set text property set to center
          ctx.fillText("your name",375,220); //text here is written dead in the actual pass an additional parameter on OK
          var img3 = new Image();
          img3.src = code;
          img3.onload = function() {
              ctx.drawImage(img3,136,554,478,478); // add the image in the same way
              var imgCode = convertCanvasToImage(canvas); //convert the image to base64
              console.log(imgCode.getAttribute('src'))
          }

         }
    }

}
imageToCanvas(canvas,"1.png",'3.jpeg','code.png'); //initialize


function convertCanvasToImage(canvas) {
    var image = new Image(); 
    image.src = canvas.toDataURL("image/png"); //convert canvas to img
    return image;
}

これでbase64が得られ、それを利用することができます。

今回の記事は以上です。皆さんの勉強のお役に立てれば幸いです。そして、スクリプトハウスを応援していただければ幸いです。