Canvas教程:拼图,组合图像,画圆形图像,添加二维码logo,添加文字
1,创建canvas对象
// method 1 document.createElement('canvas') // method 2 <canvas id="canvas" /> document.getElementById('canvas')
2,设置大小并初始化上下文
canvas.width = 341; canvas.height = 512; var ctx = canvas.getContext('2d');
3,在canvas上面添加文字,若有图像,最后添加文字,避免被覆盖
ctx.font = 'bold 20px Arial'; ctx.fillStyle = '#058'; ctx.fillText('我爱你', 150, 180); ctx.strokeStyle = 'rgba(255,255,255,0.4)'; ctx.strokeText('我爱你', 150, 180);
4,添加背景图像
var img = new Image(); img.src = 'bg.jpg'; img.onload = function() { var width = img.width / 2; var height = img.height / 2; // 背景图像加载后画到canvas画布上 ctx.drawImage(img, 0, 0, width, height); }
5,添加二维码图像即组图
// https://github.com/davidshimjs/qrcodejs <div id="qrcode" style="display: none"></div> new QRCode($('qrcode'), { text: 'http://qiaolevip.iteye.com', width: 128, height: 128, colorDark : '#000000', colorLight : '#ffffff', correctLevel : QRCode.CorrectLevel.H }); var img = $('qrcode').querySelector('img'); // 二维码图像画到canvas画布上 ctx.drawImage(img, 0, 0, width, height);
6,logo叠加添加到二维码上面即组图
var img = new Image(); img.src = 'logo.jpg'; img.onload = function() { var width = img.width / 2; var height = img.height / 2; // 背景图像加载后画到canvas画布上 ctx.drawImage(img, 0, 0, width, height); }
7,绘制圆形logo图像
ctx.save(); // 保存当前ctx的状态 ctx.arc(x+a/2, y+a/2, a/2, 0, 2 * Math.PI); //画出圆 ctx.clip(); ctx.drawImage(img, x, y, a, b); // 在刚刚裁剪的园上画图 ctx.restore(); // 还原状态
8,最终效果图呈现形式:
更多实例应用扫码体验:
相关推荐
大地飞鸿 2020-11-12
星星有所不知 2020-10-12
jinxiutong 2020-07-26
MIKUScallion 2020-07-05
songfens 2020-07-05
songfens 2020-06-11
songfens 2020-06-08
northwindx 2020-05-31
northwindx 2020-05-31
northwindx 2020-05-27
northwindx 2020-05-25
MIKUScallion 2020-05-25
jinxiutong 2020-05-10
xdyangxiaoromg 2020-05-10
大地飞鸿 2020-05-06
northwindx 2020-04-25