在 2D 画布中,有没有办法给精灵一个轮廓? [英] In a 2D canvas, is there a way to give a sprite an outline?
问题描述
我想在角色被治愈/损坏/无论如何时给精灵一个轮廓,但我想不出使用二维画布对其进行编码的方法.如果可能的话,我认为这将是一个全局复合操作,但我想不出用其中一个来实现它的方法.
I'd like to give a sprite an outline when the character gets healed/damaged/whatever but I can't think of a way to code this using the 2d canvas. If it were possible, I'd think it would be a global composite operation, but I can't think of a way to achieve it with one of them.
我确实发现了这个 stackoverflow 答案,它建议创建一个更胖的原色纯色版本,并将原来在它上面.这会给它一个大纲,但似乎需要做很多额外的工作,尤其是考虑到我正在使用占位符艺术.有没有更简单的方法?
I did find this stackoverflow answer that recommends creating a fatter, solid color version of the original and put the original on top of it. That would give it an outline, but it seems like a lot of extra work especially considering I'm using placeholder art. Is there an easier way?
这个问题与链接的问题不同,因为这是专门关于 HTML5 2D 画布的.它可能有其他问题没有的解决方案.
This question is different from the one linked because this is specifically about the HTML5 2D canvas. It may have a solution not available to the other question.
就其价值而言,我不介意轮廓是否会创建更宽的边框或使精灵保持相同的大小,我只想要轮廓外观.
For what it's worth, I don't mind if the outline creates a wider border or keeps the sprite the same size, I just want the outline look.
推荐答案
- 只需在原始图像周围的 8 个位置绘制原始图像
- 将合成模式更改为
source-in
并填充轮廓颜色 - 将合成模式改回
source-over
并在正确位置绘制原始图像 - Just draw your original image in 8 position around the original image
- Change composite mode to
source-in
and fill with the outline color - Change composite mode back to
source-over
and draw in the original image at correct location
这将创建一个干净清晰的轮廓,每边的边框厚度相等.然而,它不太适合粗轮廓.图像绘制速度很快,特别是当图像未缩放时,性能不是问题,除非您需要绘制一堆(在这种情况下,您将缓存绘图或无论如何都使用精灵表).
This will create a clean sharp outline with equal border thickness on every side. It is not so suited for thick outlines however. Image drawing is fast, especially when image is not scaled so performance is not an issues unless you need to draw a bunch (which in that case you would cache the drawings or use a sprite-sheet anyways).
示例:
var ctx = canvas.getContext('2d'),
img = new Image;
img.onload = draw;
img.src = "http://i.stack.imgur.com/UFBxY.png";
function draw() {
var dArr = [-1,-1, 0,-1, 1,-1, -1,0, 1,0, -1,1, 0,1, 1,1], // offset array
s = 2, // scale
i = 0, // iterator
x = 5, // final position
y = 5;
// draw images at offsets from the array scaled by s
for(; i < dArr.length; i += 2)
ctx.drawImage(img, x + dArr[i]*s, y + dArr[i+1]*s);
// fill with color
ctx.globalCompositeOperation = "source-in";
ctx.fillStyle = "red";
ctx.fillRect(0,0,canvas.width, canvas.height);
// draw original image in normal mode
ctx.globalCompositeOperation = "source-over";
ctx.drawImage(img, x, y);
}
<canvas id=canvas width=500 height=500></canvas>
这篇关于在 2D 画布中,有没有办法给精灵一个轮廓?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!