Changing the view “center” of an html5 canvas

[亡魂溺海] 提交于 2020-01-13 07:00:27

问题


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?


回答1:


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

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);

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.



来源:https://stackoverflow.com/questions/8592872/changing-the-view-center-of-an-html5-canvas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!