本文共 2050 字,大约阅读时间需要 6 分钟。
有的手机屏幕实际分辨率的像素比页面过去的尺寸像素要大,一遍是一倍或者两倍
var getPixelRatio = function(context) { var backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; return (window.devicePixelRatio || 1) / backingStore;};
var canvas = document.createElement('canvas')//画布var ctx = canvas.getContext("2d"); var ratio = getPixelRatio(ctx); // 获取屏幕比率canvas.width = 750*ratio; // 设置生成图片容器的宽高canvas.height = 1335*ratio; ctx.clearRect(0,0,canvas.width,canvas.height); // 设置背景颜色ctx.fillStyle = '#000000';ctx.fillRect(0,0,canvas.width, canvas.height);
function drawRound (ctx,r,x,y,img) { ctx.save() // 保存之前的 var r = r // 半径*屏幕分辨率比例 var d = 2*r // 直径 var cx = x + r // 圆弧坐标x var cy = y + r // 圆弧坐标 y ctx.arc(cx, cy, r ,0, 2*Math.PI) ctx.clip() // 裁剪 ctx.drawImage(img, x, y, d, d) // 画头像 ctx.restore() // 返回上一状态}
function drawRoundRect (ctx,r,x,y,w,h,img) { ctx.save() if (w < 2 * r) r = w / 2 if (h < 2 * r) r = h / 2 ctx.beginPath() ctx.moveTo(x+r, y) ctx.arcTo(x+w, y, x+w, y+h, r) ctx.arcTo(x+w, y+h, x, y+h, r) ctx.arcTo(x, y+h, x, y, r) ctx.arcTo(x, y, x+w, y, r) ctx.closePath(); ctx.clip() ctx.drawImage(img, x, y, w, h) ctx.restore() // 返回上一状态}
var bg = new Image()bg.crossOrigin = "*"; // 设置图片跨域问题bg.src = 'img/bg.jpg'bg.onload = function() { ctx.drawImage(bg, 0, 0, bg.width, bg.height, 0, 0, canvas.width, canvas.height); // 画完背景图后,画头像 var head = new Image() head.crossOrigin = "*" head.src = 'img/head.jpg' head.onload = function() { //画头像,这里画矩形图 var r = 10*ratio var x = 325*ratio var y = 500*ratio var w = 100*ratio var h = 100*ratio drawRoundRect(ctx,r,x,y,w,h,head) }}
正方形圆角,如下图
圆形头像,如下图
导出的数据为base64的图片链接,可以赋值到需要展示的图片上,这样就能实现图片合成的效果了
var imgData = canvas.toDataURL()
完整代码如下:
Document
转载地址:http://akhbb.baihongyu.com/