R
R
Roman2021-02-05 14:27:17
JavaScript
Roman, 2021-02-05 14:27:17

How to convert canvas shapes from one coordinate system to another when scaling width and height?

I'm trying to transfer polygon shapes from SVG to Canvas 2d, we have this SVG in a container

<div class="canvas" style="width: 8000px; height: 8000px; background-color: rgb(201, 212, 232); transform: translate3d(-3068px, -3738px, 0px);">
<svg version="1.1" height="100%" width="100%" xmlns="http://www.w3.org/2000/svg" style="overflow-x: hidden; overflow-y: hidden;">
<polygon points="0,0 555,0 555,548 165.66666666666652,548 165.66666666666652,283.16666666666697 0,283.16666666666697 0,0" etype="polygon" transform="translate(3750,3750)" fill-opacity="1"></polygon>
<polygon points="306,-210.66666666666697 471.6666666666665,-210.66666666666697 471.6666666666665,54.16666666666606 306,54.16666666666606 306,-210.66666666666697" etype="polygon" transform="translate(3444,4243.833333333334)" fill-opacity="1"></polygon>
</svg>
</div>

Then I create a canvas with the same dimensions 8000 by 8000
<canvas id='canvas' width="8000" height="8000"></canvas>
in which I draw these 2 polygons, for each of them I shift the coordinate system ctx.translate(x0, y0);as indicated in transform="translate(3750,3750)"and everything is drawn as intended.

The question is, if I need to scale the canvas size, for example, 800 by 600, how can I recalculate the coordinates of the beginning of the axis and the point of the entire figure?

What formula is better to use here, something tells me that here it is necessary to move the entire figure and redraw it, a simple scaling of the aspect ratio, as with a crop image, is unlikely to help?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MamaLuyba, 2021-02-05
@MamaLuyba

When I resized the canvas, I simply changed both it and the shapes through scale. I don’t remember if there were problems with the positioning of the figures, but in the end everything worked fine (if we talk about changing from larger to smaller).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question