S
S
Sergo Zar2021-05-09 23:09:51
JavaScript
Sergo Zar, 2021-05-09 23:09:51

A few questions about canvas?

I was without an Internet for several days and I got interested in cnavas. I decided to look in the Zeal program (brogram-collection of documentation about almost everything) what is written there and I did not understand a few things:
0. Why is the save method used before drawing something? Here is one of those examples:

function draw() {
  var ctx = document.getElementById('canvas').getContext('2d');

  // draw a simple rectangle, but scale it.
  ctx.save(); // я вот тут не понимаю, зачем сохранять "ничего"(наверное правильнее говрить "пустой холст" но я в этом не уверен)?
  ctx.scale(10, 3);
  ctx.fillRect(1, 10, 10, 10);
  ctx.restore();// и зачем это "ничего" восстанавливать?

  // mirror horizontally
  ctx.scale(-1, 1);
  ctx.font = '48px serif';
  ctx.fillText('MDN', -135, 120);
}

1. Why can't an object, such as a rectangle or a circle, be stored in a variable to make it easier to handle? For example, as in the sfml library in C ++
CircleShape circle(76,60);
circle.setOutlineThickness(2);
circle.setOutlineColor(gray);
circle.move(33,126);

Or maybe it's better to use some library for this? If yes, which one is better?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WbICHA, 2021-05-09
@Sergomen

Why is the scale method used before drawing something?

To draw something with a given scale?
ctx.save(); // I don't understand here, why save "nothing" (probably it's more correct to say "blank canvas" but I'm not sure about that)?

Because this method preserves the current canvas settings (scale, fill/stroke color, font, etc.).
ctx.restore();// and why restore "nothing"?
And then restores them.
Why can't an object, such as a rectangle or a circle, be stored in a variable to make it easier to handle?

And how do you want to store the pixels being painted in a variable? If you want to change, for this you need to store information about where to draw, what color, with what scale, etc. and redraw everything with every change.

T
tundramani, 2021-05-10
@tundramani

see Pixi.js

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question