用标签画一个不规则图形(如动物)
1,原理思路:将图片渲染到画布,然后通过getImageData拿到像素点的rgba,根据rgba找到对应坐标。
2,注意点:在调用getImageData时图片地址须在同一服务地址下,否则报跨域错误。(我是直接在vue脚手架上写的demo)
>>>模板标签
<div>
<canvas id="canvas"></canvas>
</div>
<div id="boxs"></div>
>>>css
#boxs{
position: relative;
}
>>>js(!!!我这是在vue脚手架写的demo)
mounted(){
var canvas=document.getElementById("canvas");
let boxs=document.getElementById("boxs");
var ctx=canvas.getContext("2d");
var img=new Image();
img.src=require('./black.png');
img.onload=function(){
canvas.width=img.width;
canvas.height=img.height;
ctx.drawImage(img,0,0)
var imageData=ctx.getImageData(0,0,img.width,img.height).data;
ctx.fillStyle="#ffffff";
ctx.fillRect(0,0,img.width,img.height);
var gap=12;
for(let i=0;i<img.height;i+=gap){
for(let j=0;j<img.width;j+=gap){
let p=(img.width*i+j)*4;
let R=imageData[p],G=imageData[p+1],B=imageData[p+2]
if(R+G+B==0){
let node=document.createElement("div");
node.style.left=j+"px";
node.style.top=i+"px";
node.style.position="absolute";
node.style.borderRadius="50%";
node.style.background="orange";
node.style.width=10+"px";
node.style.height=10+"px"
boxs.appendChild(node)
}
}
}
}
}