关于canvas的getImageData()函数
<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<!--<meta name="viewport" content="width=device-width">-->
<title>鱼C出品</title>
</head>
<style>
canvas{
border:1px solid red;
}
</style>
<body>
<img src="1-9.jpg" id="img"/>
<canvas id="canvas" width="2000px" height="900px"></canvas>
<script>
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var img=document.getElementById("img");
var particles=[];
//img.src="1-9.jpg";
img.onload=function(){
ctx.drawImage(img,0,0);
//ctx.clearRect(0,0,canvas.width,canvas.height);
//ctx.fillStyle="rgb(0,128,0)";
//ctx.fillRect(200,200,20,20);
//var data=imgdata.data;
//alert(data);
};
var imgdata=ctx.getImageData(0,0,900,800);
console.log(imgdata.data);
//ctx.clearRect(0,0,canvas.width,canvas.height);
function calculate(){
var cols=45,rows=40;
var s_width=parseInt(900/cols),s_height=parseInt(800/rows);
//alert(s_width);
var pos=0;
var data=imgdata.data;
//alert(data);
//alert(data.length);
for(var i=1;i<=cols;i++){
for(var j=1;j<=rows;j++){
pos=[(j*s_height-1)*900+(i*s_width-1)]*4;
//alert(data);
var particle={
x:900+i*s_width,
y:j*s_height,
fillstyle:"rgb("+data+","+data+","+data+")"
};
particles.push(particle);
}
}
}
function draw(){
//ctx.clearRect(0,0,canvas.width,canvas.height);
//alert(canvas.width);
for(var i=0;i<particles.length;i++){
ctx.fillStyle=particles.fillstyle;
ctx.fillRect(particles.x,particles.y,2,2);
//alert(particles.x+"and"+particles.y+particles.fillstyle);
}
}
calculate();
//alert(particles.length);
//ctx.clearRect(0,0,canvas.width,canvas.height);
draw();
</script>
</body>
</html>
为什么getImageData获得的都是0 找到答案了,原来是我在图片没加载完就执行后面的语句了,不过现在又有一个跨域问题,现在只有在本地搭一个服务器才能看见效果i
页:
[1]