javascript - Center image in Canvas - Stack Overflow

I have a Canvas that's 300x300 and an image that 150x150.How can I draw this image in the center o

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 badges
Add a ment  | 

2 Answers 2

Reset to default 3

For 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')

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745422978a4627048.html

相关推荐

  • javascript - Center image in Canvas - Stack Overflow

    I have a Canvas that's 300x300 and an image that 150x150.How can I draw this image in the center o

    5小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信