本篇文章为大家展示了如何用Div画条龙,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
拆解需求
遇到不靠谱的产品经理和设计师,前端工程师真是惨。我们顶着最后交付成品的巨锅,所有deadline感觉都只是用来压榨前端工程师的。
诶,画个龙
用什么画,canvas
canvas能获得指定区域的像素点阵
卧槽,有招儿了
代码时间
先用图片搜索找一张龙的剪影
将图片绘制到canvas中
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var image = new Image(); image.src = "dragon.jpg"; image.onload = function(){ canvas.width = image.width; canvas.height = image.height; ctx.drawImage(image,0,0); }
获取并裁剪画布的点阵信息
var imageData = ctx.getImageData(0,0,image.width,image.height).data; ctx.fillStyle = "#ffffff"; ctx.fillRect(0,0,image.width,image.height); var gap = 6; for (var h = 0; h < image.height; h+=gap) { for(var w = 0; w < image.width; w+=gap){ var position = (image.width * h + w) * 4; var r = imageData[position], g = imageData[position + 1], b = imageData[position + 2]; if(r+g+b==0){ ctx.fillStyle = "#000"; ctx.fillRect(w,h,4,4); } } }
现在我们获得了这样一条龙的点阵信息
通过点阵信息生成气泡dom
var dragonContainer = document.getElementById("container"); var dragonScale = 2; for (var h = 0; h < image.height; h+=gap) { for(var w = 0; w < image.width; w+=gap){ var position = (image.width * h + w) * 4; var r = imageData[position], g = imageData[position + 1], b = imageData[position + 2]; if(r+g+b==0){ var bubble = document.createElement("img"); bubble.src = "bubble.png"; bubble.setAttribute("class","bubble"); var bubbleSize = Math.random()*10+20; bubble.style.left = (w*dragonScale-bubbleSize/2) + "px"; bubble.style.top = (h*dragonScale-bubbleSize/2) + "px"; bubble.style.width = bubble.style.height = bubbleSize+"px"; bubble.style.animationDuration = Math.random()*6+4 + "s"; dragonContainer.appendChild(bubble); } } }
上述内容就是如何用Div画条龙,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注编程网行业资讯频道。