B
B
Bogdan2019-01-31 16:31:28
JavaScript
Bogdan, 2019-01-31 16:31:28

How to center an image when scaling?

How to correctly center the image when scaling, otherwise it is somehow not very centered. Most likely there is a school geometry course, but I just can’t remember how to do something.

function renderImage(canvas, scale) { 
 const context = canvas.getContext('2d');
 const canvasSize = canvas.clientWidth;
 const centerSize = canvasSize/2;
 canvas.width = canvasSize;
 canvas.height = canvasSize;
   
 const scaleKoef = (10 + scale) / 10;
 const scaleSize = canvasSize / scaleKoef;
 
  // Центрируем изображение
 const centerX = (image.width * scaleKoef / 2 - centerSize) ;
 const centerY = (image.height * scaleKoef / 2 - centerSize) ;
 
 context.drawImage(
  image, 
  centerX, centerY, scaleSize, scaleSize,
  0, 0, canvasSize, canvasSize
 );
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-02-01
@bogdan_uman

So ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question