请考虑以下片段:为什么矩形外有可见点? 上下文颜色的切换是否比矩形的绘图慢?
const templateCanvas = document.getElementById( "template" );
const tctx = templateCanvas.getContext( "2d" );
tctx.fillStyle = "red";
tctx.fillRect( 300, 300, 200, 200 )
const canvas = document.getElementById( "canvas" );
const ctx = canvas.getContext( "2d" );
const max = {
x: 800,
y: 800
};
const sites = [];
const points = 10000;
for ( let i = 0; i < points; i++ ) sites.push( {
x: Math.floor( Math.random() * max.x ),
y: Math.floor( Math.random() * max.y )
} );
const c = ( alpha ) => 'rgba(255,0,0,' + alpha + ')';
const c2 = ( alpha ) => {
let colors = [
'rgba(78,9,12,' + alpha + ')',
'rgba(161,34,19,' + alpha + ')',
'rgba(171,95,44,' + alpha + ')',
'rgba(171,95,44,' + alpha + ')',
'rgba(252,160,67,' + alpha + ')'
]
return colors[ Math.round( Math.random() * colors.length ) ];
}
sites.forEach( p => {
let imgData = tctx.getImageData( p.x, p.y, 1, 1 ).data;
ctx.fillStyle = ( imgData[ 0 ] == 255 ) ? c2( 1 ) : c2( 0 );
ctx.fillRect( p.x, p.y, 2, 2 )
} );
&#13;
<canvas id="canvas" width="800" height="800"></canvas>
<canvas id="template" width="800" height="800"></canvas>
&#13;
答案 0 :(得分:2)
我认为发生的事情是你的随机颜色函数有时会返回无效颜色,因为它是从未定义的数组元素中提取的。这是因使用Math.round()
代替Math.floor()
:
return colors[ Math.round( Math.random() * colors.length ) ];
因此,每隔一段时间就会有一个错误的颜色表达式用于填充样式,并且画布机制将忽略它。因此,您会在红色像素(正方形)覆盖的区域外获得一些点。