更改视图“中心”一个html5画布 [英] Changing the view "center" of an html5 canvas

查看:110
本文介绍了更改视图“中心”一个html5画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果图像为1024x1250且画布元素为600x800,我可以将图像绘制到画布中心,使得画布基本上是较大图像的较小视图端口。然后我想允许该中心点移动,从而产生视口正在查看图像的不同部分的错觉。

If have an image which is 1024x1250 and a canvas element that is 600x800, I can draw the image to the canvas centered such that the canvas is essentially a smaller view port of the larger image. I then want to allow that center point to move, thus creating the illusion that the viewport is viewing a different portion of the image.

现在我已经用一种很好的方式完成了这个工作,我将要查看的图像部分重新绘制到画布上,但我感觉到这种感觉这不是最佳的。有没有办法将整个图像渲染到画布,然后以某种方式转换我当前的中心点,以便这种视图转换发生在幕后,希望在某些原生层?

Right now I've done this in sort of a hokey way where I redraw the portion of the image I want to see to the canvas, but I get this feeling that this isnt optimal. Is there a way to render the whole image to the canvas and then somehow "transform" my current center point so this view shift happens behind the scenes hopefully in some native layer?

推荐答案

您可以在绘制任何图像(旋转,缩放,平移......)之前向上下文添加变换。您需要的是函数context.translate(x,y)。

You can add transformations to the context before drawing any image (rotation, scaling, translation...). What you need is the function context.translate(x,y).

然后,您只需要在(0,0)

Then, you only need to draw your image at (0,0)

例如,要显示图片的右下角部分:

For example, to display the bottom right portion of your image:

ctx.translate (-424, -450);
ctx.drawImage (image, 0, 0);

您可以查看此链接 https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Transformations 看到很多关于上下文转换的例子。

You can check this link https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Transformations to see a lot of examples on context transformation.

这篇关于更改视图“中心”一个html5画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆