Canvas 入门

创建Canvas标签,标签内部的元素会在浏览器不支持Canvas时提示
<canvas id="" width="" height="">
   <p>我是 canvas 标签内的数据 </p>
</canvas>
通过getContext判断浏览器是否支持 Canvas
<canvas id="my-canvas" width="" height="">
   <p>我是 canvas 标签内的数据 </p>
</canvas>

<script>
   var canvas = document.getElementById('my-canvas');
   if (canvas.getContext) {
       console.log('支持');
  } else {
       console.log('不支持');
  }
</script>
使用 fillText输出文本

fillText函数共有3个参数,(“文本内容”,“文本的水平位置”,“文本的垂直位置”)

<canvas id="my-canvas" width="" height="">
   <p>我是 canvas 标签内的数据 </p>
</canvas>

<script>
   var
       canvas = document.getElementById('my-canvas'),
       ctx = canvas.getContext('2d');
   ctx.fillText('文本', 13, 14);
</script>
使用 drawImagefillText为图片添加文字脚注
  • drawImage 将图片对象写到画布上,参数(“图片对象”,“图片起始水平位置”,“图片起始竖直位置”, “图片的宽”, “图片的高”)
  • fillText 将文本内容输出
  • fillStyle 设置文本的颜色
<img src="http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLFPJR06vhs1iccMd3hFzJ3GXAFm4VljTErIq6ejH3ZicIvfz9DqKxecXkKlUsZtDYYXOo9h0icQWZDw/0" alt="" id="avatar" hidden>
<canvas id="my-canvas" width="500" height="500">
   <p>我是 canvas 标签内的数据 </p>
</canvas>

<script>
   var
       canvas = document.getElementById('my-canvas'),
       avatar = document.getElementById('avatar'),
       context = canvas.getContext('2d');
   context.drawImage(avatar, 0, 0, 500, 500);
   context.fillStyle = 'cyan';
   context.fillText('文本内容', 450, 490);
</script>
使用 drawImage实现图片的合成
  • crossorigin="Anonymous" 解决跨域问题
  • toDataURL用于输出 Base64编码
<img crossorigin="Anonymous" src="https://qnlite.gtimg.com/qqnewslite/20190924/avatar/head1.png" alt="" id="border-img" hidden>
<img crossorigin="Anonymous" src="http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLFPJR06vhs1iccMd3hFzJ3GXAFm4VljTErIq6ejH3ZicIvfz9DqKxecXkKlUsZtDYYXOo9h0icQWZDw/0" alt="" id="avatar" hidden>
<img src="" alt="" id="canvas-com">
<canvas id="my-canvas" width="500" height="500" hidden>
   <p>我是 canvas 标签内的数据 </p>
</canvas>

<script src="https://code.jquery.com/jquery-3.4.1.min.js" ></script>
<script>
   var
       canvas = document.getElementById('my-canvas'),
       avatar = document.getElementById('avatar'),
       border_img = document.getElementById('border-img'),
       context = canvas.getContext('2d');
   context.drawImage(avatar, 0, 0, 500, 500);
   context.drawImage(border_img, 0, 0, 500, 500);

   data_url = canvas.toDataURL();
   $('#canvas-com').attr('src', data_url);
</script>

Canvas 中文文档