您可以使用 context.drawImage 的“剪辑”参数来抓取顶部和底部线
// clip the top 20 lines of the test canvas and put in upper canvas
ctxU.drawImage(canvas,0,0, canvas.width,20,0,0,canvasU.width,canvasU.height);
// clip th bottom 20 lines of the canvas and put in lower canvas
ctxL.drawImage(canvas,0,canvas.height-20, canvas.width,20,0,0, canvas.width,20);
然后你可以使用getImageData分析上下画布:
var imgData = ctxU.getImageData(0,0, canvasU.width, canvasU.height);
var data = imgData.data;
// vertical rows
for(var y = 0; y < canvasU.height; y++) {
// horizontal columns
for(var x = 0; x < canvasU.width; x++) {
var r = data[((canvasU.width * y) + x) * 4];
var g = data[((canvasU.width * y) + x) * 4 + 1];
var b = data[((canvasU.width * y) + x) * 4 + 2];
var a = data[((canvasU.width * y) + x) * 4 + 3];
// and then do your stuff with the rgba info
}
}
// put the edited imgData back:
这是代码和小提琴:http: //jsfiddle.net/m1erickson/66nJk/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:30px; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasU=document.getElementById("upper");
var ctxU=canvasU.getContext("2d");
var canvasL=document.getElementById("lower");
var ctxL=canvasL.getContext("2d");
// make a test canvas
var gradient=ctx.createLinearGradient(-50,0,canvas.width+50,canvas.height);
gradient.addColorStop(0.25,"red");
gradient.addColorStop(0.50,"green");
gradient.addColorStop(0.75,"blue");
ctx.beginPath();
ctx.rect(0,0,canvas.width,canvas.height);
ctx.fillStyle=gradient;
ctx.fill();
// clip the top 20 lines of the test canvas and put in upper canvas
ctxU.drawImage(canvas,0,0, canvas.width,20,0,0,canvasU.width,canvasU.height);
// clip th bottom 20 lines of the canvas and put in lower canvas
ctxL.drawImage(canvas,0,canvas.height-20, canvas.width,20,0,0, canvas.width,20);
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="upper" width=300 height=20></canvas><br>
<canvas id="canvas" width=300 height=300></canvas><br>
<canvas id="lower" width=300 height=20></canvas>
</body>
</html>