admin管理员组文章数量:1425704
I have a Canvas that's 300x300 and an image that 150x150.
How can I draw this image in the center of this Canvas. What do i write in context.translate and context.drawImage?
On what browsers will this work?
I have a Canvas that's 300x300 and an image that 150x150.
How can I draw this image in the center of this Canvas. What do i write in context.translate and context.drawImage?
On what browsers will this work?
Share Improve this question edited Dec 16, 2011 at 4:14 Russ T asked Dec 16, 2011 at 4:04 Russ TRuss T 471 silver badge5 bronze badges2 Answers
Reset to default 3For argument's sake, let's imagine your image is a rectangle.
ctx.fillRect(
(canvasWidth - width) / 2,
(canvasHeight - height) / 2,
width,
height
);
jsFiddle.
The same form of calculations apply.
the centre of the image should be placed at 150,150. the top left of the image, which is often the point used to draw things, should be places at (150-150/2),(150-150/2)
assuming that 0,0
is the top left corner. More generally top left should be at ((W-w)/2),((H-h)/2)
where W and H are the width and height of the canvas and w and h are the width and height of the image to be drawn.
(sorry if you were asking 'how do I draw an image on a canvas')
本文标签: javascriptCenter image in CanvasStack Overflow
版权声明:本文标题:javascript - Center image in Canvas - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745422977a2657984.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论