最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Center image in Canvas - Stack Overflow

programmeradmin2浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论