使用canvas怎么实现一个拼图功能?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
实现的思路其实挺简单的,主要是通过服务端获取图片链接,图片宽度,图片高度,然后利用简单的递归实现就行了(注意移动端需要采用2倍数的比例,否则会出现图片模糊的问题)
function canvasDraw(option){ var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'), clientWidth = document.documentElement.clientWidth, canvasHeight = 0, distance = 0, photoCount = 0, iconCount = 0; // canvas中手机上一倍绘图会模糊,需采用两倍,pc端不会。 clientWidth = clientWidth > 480? 480 * 2 : clientWidth * 2; option.photoData.forEach(function(item,index,picArr){ if (!index) { item.distance = 0; }else if(index){ distance += Math.floor(clientWidth / option.photoData[index - 1].width * option.photoData[index - 1].height) item.distance = distance; } canvasHeight += Math.floor(clientWidth / item.width * item.height); item.imgHeight = Math.floor(clientWidth / item.width * item.height); }) console.log(option.photoData) if (ctx) { canvas.width = clientWidth; canvas.height = canvasHeight + clientWidth / 4 * 2 ctx.fillStyle = '#fff' ctx.fillRect(0, 0, canvas.width, canvas.height) // 绘制图片文字 if(option.wordData.length){ option.wordData.forEach(function(item,index){ ctx.fillStyle = item.color; ctx.font = 'normal normal ' + item.fontWeight + ' ' + calculate(item.fontSize) + 'px Microsoft YaHei'; ctx.textAlign = 'left'; ctx.fillText(item.word, calculate(item.left), canvasHeight + calculate(item.top)); }) } //按比例计算不同手机的百分比间距 function calculate(num){ return Math.floor(clientWidth * num / 750) } drawPhoto('photo0') function drawPhoto(photoDom){ var photoDom = new Image(); photoDom.setAttribute('crossOrigin', 'Anonymous'); photoDom.src = option.photoData[photoCount].photo; photoDom.onload = function(){ ctx.drawImage(photoDom, 0, option.photoData[photoCount].distance, clientWidth, option.photoData[photoCount].imgHeight); photoCount++; if (photoCount == option.photoData.length) { drawIcon('icon0') function drawIcon(iconDom){ var iconDom = new Image(); iconDom.setAttribute('crossOrigin', 'Anonymous'); iconDom.src = option.iconData[iconCount].icon; iconDom.onload = function(){ ctx.drawImage(iconDom, calculate(option.iconData[iconCount].left), canvasHeight + calculate(option.iconData[iconCount].top), calculate(option.iconData[iconCount].width), calculate(option.iconData[iconCount].height)) iconCount++; if (iconCount == option.iconData.length) { var imageURL = canvas.toDataURL("image/jpeg") document.getElementsByClassName('shareImg')[0].setAttribute('src', imageURL) //将闭包引用清除,释放内存; drawPhoto = null; }else{ drawIcon('icon' + iconCount) } } } }else{ drawPhoto('photo'+ photoCount) } } } }else{ console.log('不支持canvas') } }
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注编程网行业资讯频道,感谢您对编程网的支持。