Форум программистов, компьютерный форум, киберфорум
JavaScript: HTML5 Canvas
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.60/15: Рейтинг темы: голосов - 15, средняя оценка - 4.60
0 / 0 / 0
Регистрация: 03.12.2017
Сообщений: 14

Мельница (анимация)

19.05.2019, 14:08. Показов 3225. Ответов 9
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Доброго времени суток. Немного постигаю анимацию на JavaScript, и вот сейчас потребовалось сделать мельницу: грубо говоря, два вращающихся прямоугольника с линией
Два вращающихся прямоугольника получаются, а вот прямая - нет, на мгновение она появляется, а потом исчезает. Что делать в таком случае?

Прилагаю код без прямой линии, просто прямоугольники
PHP/HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Мельница</title>
</head>
<body>
 
<canvas id="myCanvas"></canvas>
 
<script>
 
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
 
    var width = 500,
        height = 300;
 
    canvas.width = width;
    canvas.height = height;
 
    ctx.save();
    ctx.translate(100, -60);
 
    var drawRect = function (x, y, w, h, a) {
        var dx = x + w / 2;
        var dy = y + h / 2;
 
        if (a) {
            a = a * (Math.PI / 180);
            ctx.save();
            ctx.translate(dx, dy);
            ctx.rotate(a);
            ctx.translate(-dx, -dy);
        }
 
        ctx.strokeRect(x, y, w, h)
 
        if (a) {
            ctx.restore();
        }
 
    };
 
    var x = 100,
        y = 100,
        a = 0;
 
    setInterval(function() {
        ctx.clearRect(0, 0, width, height);
        drawRect(x, y, 100, 100, a);
 
        ctx.save();
        ctx.translate(150, -60);
        ctx.rotate(45*Math.PI/180);
        drawRect(x, y, 100, 100, a);
        ctx.restore();
        a += 1;
    }, 50 );  
 
</script>
 
</body>
</html>
0
Лучшие ответы (1)
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
19.05.2019, 14:08
Ответы с готовыми решениями:

Ветряная мельница
Надо изобразить работающую ветряную мельницу. Сам дом есть, лопасти есть и даже крутятся, но вмести с домиком. Помогите поставить саму...

Модуль Граф АВС Мельница
пожалуйста, помогите нарисовать мельницу! в АВС... вот код рисунка... я что мог то нарисовал... все лишние строки которые тут есть...

Нарисована мельница с 4 вращающимися лопастями. А двигаются только 2 лопасти
Помогите найти ошибку. Нарисована мельница с 4 вращающимися лопастями. А двигаются только 2 лопасти Program mill; uses crt, ...

9
Эксперт JSЭксперт HTML/CSS
2151 / 1496 / 651
Регистрация: 16.04.2016
Сообщений: 3,696
19.05.2019, 15:24
Лучший ответ Сообщение было отмечено Kotybird как решение

Решение

https://jsfiddle.net/Qwerty_Wasd/3t9xos7u/
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
 
    var width = 500,
        height = 300;
 
    canvas.width = width;
    canvas.height = height;
 
    ctx.save();
    ctx.translate(100, -60);
 
    var drawRect = function (x, y, w, h, a) {
        var dx = x + w / 2;
        var dy = y + h / 2;
 
        if (a) {
            a = a * (Math.PI / 180);
            ctx.save();
            ctx.translate(dx, dy);
            ctx.rotate(a);
            ctx.translate(-dx, -dy);
        }
 
        ctx.strokeRect(x, y, w, h)
 
        if (a) {
            ctx.restore();
        }
 
    };
 
    var x = 100,
        y = 100,
        a = 0;
 
    setInterval(function() {
        ctx.clearRect(0, 0, width, height);
        drawRect(x, y, 100, 100, a);
        /////////////////////
        ctx.beginPath();
        ctx.moveTo(150, 150);
        ctx.lineTo(150, 600);
        ctx.stroke();
        /////////////////////
        ctx.save();
        ctx.translate(150, -60);
        ctx.rotate(45*Math.PI/180);
        drawRect(x, y, 100, 100, a);
        ctx.restore();
        a += 1;
    }, 50 );
2
0 / 0 / 0
Регистрация: 03.12.2017
Сообщений: 14
20.05.2019, 19:57  [ТС]
Спасибо! (=
0
9933 / 2936 / 494
Регистрация: 05.10.2013
Сообщений: 7,983
Записей в блоге: 239
24.05.2019, 12:45
Цитата Сообщение от Qwerty_Wasd Посмотреть сообщение
https://jsfiddle.net/Qwerty_Wasd/3t9xos7u/
TypeScript Version: Playground

VSCode Project: Вложение 1041680
Code
1
npm run build
Program.ts

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { Windmill } from "./Windmill";
 
class Program
{
    public static Main(): void
    {
        // Retrieve a canvas
        let canvas = document.getElementById("myCanvas") as HTMLCanvasElement;
        // Get a context
        let ctx = canvas.getContext("2d");
 
        // Create and run a windmill
        let windmill = new Windmill(ctx);
        windmill.Run();
    }
}
Program.Main();
Windmill.ts

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
export class Windmill
{
    private _ctx: CanvasRenderingContext2D;
    private _width = 500;
    private _height = 300;
    private _x = 100;
    private _y = 100;
    private _angle = 0;
 
    public constructor(ctx: CanvasRenderingContext2D)
    {
        this._ctx = ctx;
 
        this._ctx.canvas.width = this._width;
        this._ctx.canvas.height = this._height;
 
        this._ctx.save();
        this._ctx.translate(100, -60);
    }
 
    public Run(): void
    {
        this._ctx.clearRect(0, 0, this._width, this._height);
        this.DrawRect(this._x, this._y, 100, 100, this._angle);
        /////////////////////
        this._ctx.beginPath();
        this._ctx.moveTo(150, 150);
        this._ctx.lineTo(150, 600);
        this._ctx.stroke();
        /////////////////////
        this._ctx.save();
        this._ctx.translate(150, -60);
        this._ctx.rotate(45 * Math.PI / 180);
        this.DrawRect(this._x, this._y, 100, 100, this._angle);
        this._ctx.restore();
        this._angle += 1;
        requestAnimationFrame(() => this.Run());
    }
 
    private DrawRect(x: number, y: number, w: number, h: number, angle?: number)
    {
        let dx = x + w / 2;
        let dy = y + h / 2;
 
        if (angle)
        {
            angle = angle * (Math.PI / 180);
            this._ctx.save();
            this._ctx.translate(dx, dy);
            this._ctx.rotate(angle);
            this._ctx.translate(-dx, -dy);
        }
 
        this._ctx.strokeRect(x, y, w, h)
 
        if (angle)
        {
            this._ctx.restore();
        }
    }
}
1
9933 / 2936 / 494
Регистрация: 05.10.2013
Сообщений: 7,983
Записей в блоге: 239
24.05.2019, 12:51
VSCode Project: windmill.zip
npm run build
0
Эксперт JSЭксперт HTML/CSS
2151 / 1496 / 651
Регистрация: 16.04.2016
Сообщений: 3,696
24.05.2019, 17:56
8Observer8, hi!
Цитата Сообщение от 8Observer8 Посмотреть сообщение
npm run build
Are you seeing topicstarter code ? I think - you showed him work Node.js early

By the way, try this sandbox - https://codesandbox.io/
0
9933 / 2936 / 494
Регистрация: 05.10.2013
Сообщений: 7,983
Записей в блоге: 239
24.05.2019, 18:20
Цитата Сообщение от Qwerty_Wasd Посмотреть сообщение
By the way, try this sandbox - https://codesandbox.io/
Does this sandbox work with a few TypeScript files? Can it build in AMD modules like https://plnkr.co/edit/ ? Plunker allows to build AMD modules and use it with RequireJS library. Why do you think that https://codesandbox.io/ is better?

Цитата Сообщение от Qwerty_Wasd Посмотреть сообщение
Are you seeing topicstarter code ? I think - you showed him work Node.js early
I rewrote your code to TypeScript because I learn TypeScript and I need a practice. I sure that TypeScript is better than JavaScript. I will rewrite all my code and all interesting examples to TypeScript. I practice with TypeScript for myself only. But I hope that my example with be useful for someone in the future. TypeScript is really better that JavaScript. I will not explain why because I do not want to spend my time. It is better to spend my time for creating simple games in TypeScript for practice.

Добавлено через 4 минуты
Цитата Сообщение от Qwerty_Wasd Посмотреть сообщение
By the way, try this sandbox - https://codesandbox.io/
Thank you. But this sandbox is very complicated for me. I do not need Angular. I need plain TypeScript only. Plunker is better and more simple for me.

Добавлено через 5 минут
Цитата Сообщение от Qwerty_Wasd Посмотреть сообщение
I think - you showed him work Node.js early
He can just download my example windmill.zip, make some changes, and compile code from TypeScript to JavaScript using this command:
npm run build
This command just runs this command:
"build": "tsc -p tsconfig.amd.client.json"
Result files will be in the "dist_client" directory.
0
Эксперт JSЭксперт HTML/CSS
2151 / 1496 / 651
Регистрация: 16.04.2016
Сообщений: 3,696
24.05.2019, 18:42
Цитата Сообщение от 8Observer8 Посмотреть сообщение
Does this sandbox work with a few TypeScript files? Can it build in AMD modules like https://plnkr.co/edit/ ? Plunker allows to build AMD modules and use it with RequireJS library.
easily. Enough study the functionality.
Цитата Сообщение от 8Observer8 Посмотреть сообщение
Why do you think that https://codesandbox.io/ is better?
I don't said - "better". This alternative. Pretty comfortable.
Цитата Сообщение от 8Observer8 Посмотреть сообщение
But this sandbox is very complicated for me. I do not need Angular. I need plain TypeScript only.
so offered .

Цитата Сообщение от 8Observer8 Посмотреть сообщение
I rewrote your code to TypeScript
not my code, I just added piece of code for topicstarter.

Цитата Сообщение от 8Observer8 Посмотреть сообщение
I will not explain why because I do not want to spend my time. It is better to spend my time for creating simple games in TypeScript for practice.
I apologize, dare not distract.
0
9933 / 2936 / 494
Регистрация: 05.10.2013
Сообщений: 7,983
Записей в блоге: 239
24.05.2019, 19:37
Цитата Сообщение от Qwerty_Wasd Посмотреть сообщение
easily. Enough study the functionality.
Realy? Is it very simple? Without Angular? Could you public this "Hello, World" example with a few files on the Sandbox? You can just copy my example. It will take maybe 30 seconds. But I think it is not so simple like on Plunker. Please, show me that it is very easy.

My example on Plunker Sandbox

Source Code: person-say-hello.zip

Output:
Hello, I am Jack
Hello, I am Bob
Program.ts

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { Person } from "./Person";
 
class Program
{
    public static Main(): void
    {
        let jack = new Person("Jack");
        jack.SayHello();
 
        let bob = new Person("Bob");
        bob.SayHello();
    }
}
Program.Main();
Person.ts

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { Output } from "./Output";
 
export class Person
{
    private _name: string;
 
    public constructor(name: string)
    {
        this._name = name;
    }
 
    public SayHello(): void
    {
        Output.Instance.Print(`Hello, I am ${this._name}`);
    }
}
Output.ts

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Singleton for output messages
export class Output
{
    private static _instance: Output;
    private _outputElement: HTMLDivElement;
 
    private constructor()
    {
        this._outputElement = document.createElement("div");
        document.body.appendChild(this._outputElement);
    }
 
    public static get Instance(): Output
    {
        if (!this._instance)
        {
            this._instance = new Output();
        }
 
        return this._instance;
    }
 
    public Print(message: string): void
    {
        this._outputElement.innerHTML += message;
        this._outputElement.innerHTML += "<br>";
    }
}
1
Эксперт JSЭксперт HTML/CSS
2151 / 1496 / 651
Регистрация: 16.04.2016
Сообщений: 3,696
24.05.2019, 21:02
8Observer8, you are right - this combo not work on that sandbox. Just tried - conflicts
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
24.05.2019, 21:02
Помогаю со студенческими работами здесь

Как разобрать редуктор кофемолки Saeco/Gaggia? Засорилась мельница
Вот навалилось. Вызвали ещё на одну кофемашину, и та же беда- Grinder blocked. У Saeco и Gaggia много узлов одинаковых. Вот кофемолки...

Кофеварка Saeco Royal Digital, Перколатор и мельница работают одновременно
Не могу справиться с проблемой Saeco Royal Digital. При прохождении теста включения вместе с двигателем перколатора включается кофемолка....

Анимация в OpenGL, а где собсно, анимация?
// Bounce.cpp // Demonstrates a simple animated rectangle program with GLUT // OpenGL SuperBible, 3rd Edition // Richard S. Wright...

Анимация
Добрый вечер! Можно активировать css анимацию при ховере, клике и другим событиям, а как сделать так, чтобы анимация проигрывалась при...

Анимация
Привет Всем. Такой вопрос, добавляю запись в таблицу $('#spis').append('&lt;tr id='+i+' &quot;&gt;&lt;td&gt;'+json.last_name+' '+json.first_name+'...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
10
Ответ Создать тему
Новые блоги и статьи
SDL3 для Desktop (MinGW): Создаём пустое окно с нуля для 2D-графики на SDL3, Си и C++
8Observer8 10.03.2026
Содержание блога Финальные проекты на Си и на C++: hello-sdl3-c. zip hello-sdl3-cpp. zip Результат:
Установка CMake и MinGW 13.1 для сборки С и C++ приложений из консоли и из Qt Creator в EXE
8Observer8 10.03.2026
Содержание блога MinGW - это коллекция инструментов для сборки приложений в EXE. CMake - это система сборки приложений. Здесь описаны базовые шаги для старта программирования с помощью CMake и. . .
Как дизайн сайта влияет на конверсию: 7 решений, которые реально повышают заявки
Neotwalker 08.03.2026
Многие до сих пор воспринимают дизайн сайта как “красивую оболочку”. На практике всё иначе: дизайн напрямую влияет на то, оставит человек заявку или уйдёт через несколько секунд. Даже если у вас. . .
Модульная разработка через nuget packages
DevAlt 07.03.2026
Сложившийся в . Net-среде способ разработки чаще всего предполагает монорепозиторий в котором находятся все исходники. При создании нового решения, мы просто добавляем нужные проекты и имеем. . .
Модульный подход на примере F#
DevAlt 06.03.2026
В блоге дяди Боба наткнулся на такое определение: В этой книге («Подход, основанный на вариантах использования») Ивар утверждает, что архитектура программного обеспечения — это структуры,. . .
Управление камерой с помощью скрипта OrbitControls.js на Three.js: Вращение, зум и панорамирование
8Observer8 05.03.2026
Содержание блога Финальная демка в браузере работает на Desktop и мобильных браузерах. Итоговый код: orbit-controls-threejs-js. zip. Сканируйте QR-код на мобильном. Вращайте камеру одним пальцем,. . .
SDL3 для Web (WebAssembly): Синхронизация спрайтов SDL3 и тел Box2D
8Observer8 04.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-sync-physics-sprites-sdl3-c. zip На первой гифке отладочные линии отключены, а на второй включены:. . .
SDL3 для Web (WebAssembly): Идентификация объектов на Box2D v3 - использование userData и событий коллизий
8Observer8 02.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-collision-events-sdl3-c. zip Сканируйте QR-код на мобильном и вы увидите, что появится джойстик для управления главным героем. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru