Html 在画布中间绘制图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16317971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Draw images on in the middle of a canvas
提问by Matt
I'm making a photogallery, but all my images are painted in the origin (0,0).
我正在制作一个相册,但我所有的图像都是在原点 (0,0) 中绘制的。
canvasContent.drawImage(arrPhoto[currentIndex], 0, 0);
How can I make sure that my images are drawn in the middle on the canvas object?
如何确保我的图像绘制在画布对象的中间?
Thanks for helping me out!
谢谢你的协助!
UPDATE
更新
I might have formed my question a bit wrong. What I mean is: I want the middle of my image to be in the middle of my canvas, not the top corner of the image.
我的问题可能有点错误。我的意思是:我希望图像的中间位于画布的中间,而不是图像的顶角。
Sorry for that
对不起
Edit: typo
编辑:错字
Edit2: typo
编辑2:错字
回答by Mark Rhodes
If you supply the x, y
position like so:
如果你提供这样的x, y
位置:
var image = arrPhoto[currentIndex];
canvasContent.drawImage(image,
canvas.width / 2 - image.width / 2,
canvas.height / 2 - image.height / 2
);
then it should appear in the center. An example of this in action is available at: http://jsfiddle.net/VPLZc/2/.
那么它应该出现在中心。可以在以下位置找到此操作的示例:http: //jsfiddle.net/VPLZc/2/。
回答by Andrei Nemes
If you want to draw it dead on into the centre, you need to know the image width and height. It becomes easy afterwards:
如果你想把它画在中心,你需要知道图像的宽度和高度。之后就变得容易了:
//var canvas = document.getElementById("yourCanvasElementID");
var img = arrPhoto[currentIndex];
canvasContent.drawImage(img, (canvas.width-img.width)/2, (canvas.height-img.height)/2);
回答by Glitch Desire
Offset the origin (which is always 0,0 -- top left) by + (image.width / 2)
and + (image.height / 2)
to start drawing in the centre of the canvas.
将原点(始终为 0,0 -- 左上角)偏移+ (image.width / 2)
和+ (image.height / 2)
以在画布的中心开始绘制。
drawImage(image, image.width/2, image.height/2)