【发布时间】:2016-02-24 16:39:56
【问题描述】:
我正在制作一个渲染游戏对象(Project Zomboid 僵尸)位置的地图:
当用户缩小时,单点不再有用。相反,我想使用红色渐变渲染僵尸在区域上的分布。我尝试循环遍历每个渲染像素的所有僵尸,并将其着色为与僵尸距离平方和的倒数。结果:
这太模糊了。此外,结果更多地受到远离点的僵尸的影响——我需要更多地受到接近的僵尸的影响。所以这只是数学。这是我使用的代码:
var h = canvas.height;
var w = canvas.width;
// To loop over more than 1 pixel (performance)
var tileSize = 10;
var halfRadius = Math.floor(tileSize/2);
var time = performance.now();
// "Squared" because we didnt unsquare it
function distanceSquared(A, B) {
return (A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y);
}
// Loop for every x,y pixel (or region of pixels)
for(var y=0; y<h; y+=tileSize) {
for(var x=0; x<w; x+=tileSize) {
// Time security - stop rendering after 1 second
if(performance.now()-time>1000) {
x=w;y=h;break;
}
// Convert relative canvas offset to absolute point on the map
var point = canvasPixeltoImagePixel(x, y);
// For every zombie add sqrt(distance from this point to zombie)
var distancesRoot = 0;
// Loop over the zombies
var zombieCoords;
for(var i=0; i<zombies_length; i++) {
// Get single zombie coordinates as {x:0, y:0}
if((coords=zombies[i].pixel)==null)
coords = zombies[i].pixel = tileToPixel(zombies[i].coordinates[0], zombies[i].coordinates[1], drawer);
// square root is a) slow and b) probably not what I want anyway
var dist = distanceSquared(coords, point);
distancesRoot+=dist;
}
// The higher the sum of distances is, the more intensive should the color be
var style = 'rgba(255,0,0,'+300000000/distancesRoot+')';
// Kill the console immediatelly
//console.log(style);
// Maybe we should sample and cache the transparency styles since there's limited ammount of colors?
ctx.fillStyle = style;
ctx.fillRect(x-halfRadius,y-halfRadius,tileSize,tileSize);
}
}
我对如何做的理论解释很好,但如果你用一些要点制作简单的画布示例,那会很棒。
【问题讨论】:
-
如果你能建立那个基础小提琴,我想我们中的一些人现在已经回答了。我想知道如果只有一个带有 0.6 globalAlpha 的径向渐变还不够整洁。 (在绘制弧线之前使用 ctx.scale)。
-
你的描述听起来像heatmap。
标签: javascript math html5-canvas gradient