代码整理-js合并图片
说明
- js将两张图片合并为一张,比如一键生成海报图(将二维码合并到海报图上)
操作
html代码
<!DOCTYPE html> <html> <head> <title>js合并图片</title> </head> <body> <canvas id="canvas"></canvas> <script type="text/javascript" src="index.js"></script> </body> </html>
js代码
// 加载图片 var img1 = new Image(); img1.src = '1.jpg'; var img2 = new Image(); img2.src = '2.jpg'; img1.onload = function() { //获取canvas元素 var canvas = document.getElementById("canvas"); canvas.width = img1.width; canvas.height = img1.height; var ctx = canvas.getContext("2d"); ctx.rect(0, 0, canvas.width, canvas.height); ctx.fillStyle = "#F7F8FA"; ctx.fill(); //将图片1绘制到canvas上 ctx.drawImage(img1, 0, 0); img2.onload = function() { //将图片2绘制到canvas上 ctx.drawImage(img2, canvas.width - 150, canvas.height - 150, 100, 100); }; };