javascript HTML画布:如何绘制翻转/镜像图像?

nwnhqdif  于 10个月前  发布在  Java
关注(0)|答案(4)|浏览(116)

当我在HTML画布上绘制图像时,我试图翻转/镜像图像;我发现了一个游戏教程,显示了一个角色必须面对的每个方向的精灵表,但这似乎不太对我。特别是因为每个帧具有不同的大小。
达到这个目标的最佳技术是什么?
我尝试在画布上调用setScale(-1, 1);,但没有成功。也许这不是为了这个。
谢啦,谢啦

jw5wzhpr

jw5wzhpr1#

1.但是,您可以在绘制图像之前使用myContext.scale(-1,1)转换上下文来完成此操作
1.这会拖慢你的比赛。这是一个更好的主意,有一个单独的,扭转精灵。

ac1kyiln

ac1kyiln2#

您需要设置画布的比例以及反转宽度。

function drawToCanvas(img, context, width, height){
    context.save();
    context.scale(-1, 1);
    context.drawImage(img, 0, 0, width*-1, height);
    context.restore();
}

字符串
可能有一些性能问题,但对我来说,这不是一个问题。

nhjlsmyf

nhjlsmyf3#

如果你只是水平地翻转它,它会离开边界…因此使用translate调整其位置:

ctx.translate(canvas.width, 0);
ctx.scale(-1, 1);
ctx.drawImage(img, 0, 0);

字符串
对于较短的代码,您可以删除translate,并在drawImage(x坐标)的第二个参数中使用图像大小作为负偏移量:

ctx.scale(-1, 1);
ctx.drawImage(img, canvas.width * -1, 0);


如果您想稍后恢复上下文,请在其前后添加save/restore

ctx.save();
ctx.scale(-1, 1);
ctx.drawImage(img, canvas.width * -1, 0);
ctx.restore();

uhry853o

uhry853o4#

创建反射时不需要重绘整个图像。原始反射仅显示图像的底部。这样你重绘的是图像的一小部分,这提供了更好的性能,而且你不需要创建线性渐变来隐藏图像的下部(因为你从来没有画过它)。

var img = new Image();
 img.src = "//vignette2.wikia.nocookie.net/tomandjerryfan/images/9/99/Jerry_Mouse.jpg/revision/latest?cb=20110522075610";
 img.onload = function() {
   var thumbWidth = 250;
   var REFLECTION_HEIGHT = 50;
   var c = document.getElementById("output");
   var ctx = c.getContext("2d");
   var x = 1;
   var y = 1;

	//draw the original image
   ctx.drawImage(img, x, y, thumbWidth, thumbWidth);
	ctx.save();
	//translate to a point from where we want to redraw the new image
   ctx.translate(0, y + thumbWidth + REFLECTION_HEIGHT + 10);
   ctx.scale(1, -1);
   ctx.globalAlpha = 0.25;
   
   //redraw only bottom part of the image
   //g.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
   ctx.drawImage(img, 0, img.height - REFLECTION_HEIGHT, img.width, REFLECTION_HEIGHT, x, y, thumbWidth, REFLECTION_HEIGHT);

   // Revert transform and scale
  ctx.restore();

 };
body {
   background-color: #FFF;
   text-align: center;
   padding-top: 10px;
 }
<canvas id="output" width="500" height="500"></canvas>

相关问题