JQuery WEBサービス

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Interactive Web Page</title>
    <style>
        .highlight {
            color: blue;
            font-weight: bold;
        }
        .listItem {
            cursor: pointer;
        }
        #inputField::placeholder {
            color: #999; /* ヒントテキストの色を設定 */
        }
    </style>
</head>
<body>

<h1>Interactive Web Page</h1>

<p>Type something in the input box below and click 'Add' to add it to the list:</p>

<input type="text" id="inputField" placeholder="Type here...">
<span id="charCount">0</span> characters
<button id="addButton">Add</button>

<ul id="listContainer">
    <!-- Items will be dynamically added here -->
</ul>

<script src="script.js"></script>
</body>
</html>

script.js

document.addEventListener("DOMContentLoaded", function() {
    var inputField = document.getElementById("inputField");
    var charCount = document.getElementById("charCount");
    var addButton = document.getElementById("addButton");
    var listContainer = document.getElementById("listContainer");

    inputField.addEventListener("input", function() {
        // 入力された文字数を更新
        charCount.textContent = inputField.value.length;
    });

    inputField.addEventListener("focus", function() {
        // 入力フォームがフォーカスされたときにヒントテキストを非表示にする
        inputField.placeholder = "";
    });

    inputField.addEventListener("blur", function() {
        // 入力フォームがフォーカスを失ったときにヒントテキストを再表示する
        inputField.placeholder = "Type here...";
    });

    addButton.addEventListener("click", function() {
        var userInput = inputField.value.trim();

        if (userInput !== "") {
            var listItem = document.createElement("li");
            var now = new Date(); // 現在の日時を取得
            listItem.textContent = userInput + " - " + now.toLocaleString(); // テキストと日時を結合して表示
            listItem.classList.add("listItem");

            // リストアイテムを追加する際にアニメーションを付ける
            listItem.style.opacity = "0"; // 最初は透明に設定
            listContainer.appendChild(listItem);
            listItem.style.transition = "opacity 0.5s"; // アニメーションの設定
            listItem.offsetHeight; // レンダリングをトリガーするためのダミー
            listItem.style.opacity = "1"; // 透明度を元に戻す

            inputField.value = "";
            charCount.textContent = "0"; // 文字数をリセット

            listItem.addEventListener("click", function() {
                listItem.classList.toggle("highlight"); // リストアイテムがクリックされたときに強調表示を切り替える
            });
        }
    });
});

jQuery style

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQueryの練習</title>
    <style>
        .red-text{
            color: red;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <button>Go!</button>
    <p>こんにちは!</p>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    <script src="js/main.js"></script>
</body>
</html>

main.js

'use strict';

$(() => {
    $('button').click(() => {
        // $('p').text('おはよう!');
        // $('p').addClass('red-text');

          $('p')
          .text('おはよう!')
        .addClass('red-text'); 
    });
});

Javascript style属性

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My JavaScript</title>
</head>
<body>
  <p style="color: red;">Hello</p>
  <button>OK</button>
  
  <script src="main.js"></script>
</body>
</html>

main.js

'use strict';

{
  document.querySelector('button').addEventListener('click', () => {
    //document.querySelector('p').style = 'font-size: 24px';
    document.querySelector('p').style.fontSize = '24px';
  });
}

Javascript お絵描きアプリ

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Drawing App</title>
<style>
    canvas {
        border: 2px solid #000;
        cursor: crosshair;
    }
    #toolbar {
        margin-bottom: 10px;
    }
</style>
</head>
<body>
<div id="toolbar">
    <label for="colorPicker">Color:</label>
    <input type="color" id="colorPicker" value="#000">
    <label for="thickness">Thickness:</label>
    <input type="range" id="thickness" min="1" max="20" value="5">
    <button id="pencil">Pencil</button>
    <button id="line">Line</button>
    <button id="rectangle">Rectangle</button>
    <button id="circle">Circle</button>
    <button id="undo">Undo</button>
    <button id="redo">Redo</button>
    <button id="clear">Clear</button>
</div>
<canvas id="drawingCanvas" width="800" height="600"></canvas>

<script>
    const canvas = document.getElementById('drawingCanvas');
    const context = canvas.getContext('2d');
    let isDrawing = false;
    let lastX = 0;
    let lastY = 0;
    let color = '#000';
    let thickness = 5;
    let isEraser = false;
    let lines = [];
    let currentLine = null;

    function startDrawing(e) {
        isDrawing = true;
        [lastX, lastY] = [e.offsetX, e.offsetY];
        currentLine = {
            color,
            thickness,
            points: [{ x: lastX, y: lastY }]
        };
    }

    function stopDrawing() {
        isDrawing = false;
        if (currentLine) {
            lines.push(currentLine);
            currentLine = null;
        }
    }

    function draw(e) {
        if (!isDrawing) return;

        const x = e.offsetX;
        const y = e.offsetY;

        context.beginPath();
        context.moveTo(lastX, lastY);
        context.lineTo(x, y);
        context.strokeStyle = isEraser ? '#fff' : color;
        context.lineWidth = isEraser ? thickness * 2 : thickness;
        context.lineCap = 'round';
        context.stroke();

        currentLine.points.push({ x, y });

        [lastX, lastY] = [x, y];
    }

    function changeColor(e) {
        color = e.target.value;
    }

    function changeThickness(e) {
        thickness = e.target.value;
    }

    function toggleEraser() {
        isEraser = !isEraser;
        document.getElementById('pencil').textContent = isEraser ? 'Pencil' : 'Eraser';
    }

    function drawLine() {
        isEraser = false;
        document.getElementById('pencil').textContent = 'Pencil';
        canvas.removeEventListener('mousedown', startDrawing);
        canvas.removeEventListener('mousemove', draw);
        canvas.removeEventListener('mouseup', stopDrawing);
        canvas.removeEventListener('mouseout', stopDrawing);
        canvas.addEventListener('mousedown', startDrawing);
        canvas.addEventListener('mousemove', drawLinePreview);
        canvas.addEventListener('mouseup', drawLineFinish);
        canvas.addEventListener('mouseout', drawLineFinish);
    }

    function drawLinePreview(e) {
        if (!isDrawing) return;

        context.clearRect(0, 0, canvas.width, canvas.height);
        context.beginPath();
        context.moveTo(lastX, lastY);
        context.lineTo(e.offsetX, e.offsetY);
        context.strokeStyle = color;
        context.lineWidth = thickness;
        context.lineCap = 'round';
        context.stroke();
    }

    function drawLineFinish(e) {
        if (!isDrawing) return;

        context.clearRect(0, 0, canvas.width, canvas.height);
        draw(e);
        canvas.removeEventListener('mousemove', drawLinePreview);
        canvas.removeEventListener('mouseup', drawLineFinish);
        canvas.removeEventListener('mouseout', drawLineFinish);
        canvas.addEventListener('mousedown', startDrawing);
        canvas.addEventListener('mousemove', draw);
        canvas.addEventListener('mouseup', stopDrawing);
        canvas.addEventListener('mouseout', stopDrawing);
    }

    function drawRectangle() {
        isEraser = false;
        document.getElementById('pencil').textContent = 'Pencil';
        canvas.removeEventListener('mousedown', startDrawing);
        canvas.removeEventListener('mousemove', draw);
        canvas.removeEventListener('mouseup', stopDrawing);
        canvas.removeEventListener('mouseout', stopDrawing);
        canvas.addEventListener('mousedown', startDrawing);
        canvas.addEventListener('mousemove', drawRectanglePreview);
        canvas.addEventListener('mouseup', drawRectangleFinish);
        canvas.addEventListener('mouseout', drawRectangleFinish);
    }

    function drawRectanglePreview(e) {
        if (!isDrawing) return;

        context.clearRect(0, 0, canvas.width, canvas.height);
        const width = e.offsetX - lastX;
        const height = e.offsetY - lastY;
        context.strokeRect(lastX, lastY, width, height);
    }

    function drawRectangleFinish(e) {
        if (!isDrawing) return;

        const width = e.offsetX - lastX;
        const height = e.offsetY - lastY;
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.strokeRect(lastX, lastY, width, height);
        stopDrawing();
        canvas.removeEventListener('mousemove', drawRectanglePreview);
        canvas.removeEventListener('mouseup', drawRectangleFinish);
        canvas.removeEventListener('mouseout', drawRectangleFinish);
        canvas.addEventListener('mousedown', startDrawing);
        canvas.addEventListener('mousemove', draw);
        canvas.addEventListener('mouseup', stopDrawing);
        canvas.addEventListener('mouseout', stopDrawing);
    }

    function drawCircle() {
        isEraser = false;
        document.getElementById('pencil').textContent = 'Pencil';
        canvas.removeEventListener('mousedown', startDrawing);
        canvas.removeEventListener('mousemove', draw);
        canvas.removeEventListener('mouseup', stopDrawing);
        canvas.removeEventListener('mouseout', stopDrawing);
        canvas.addEventListener('mousedown', startDrawing);
        canvas.addEventListener('mousemove', drawCirclePreview);
        canvas.addEventListener('mouseup', drawCircleFinish);
        canvas.addEventListener('mouseout', drawCircleFinish);
    }

    function drawCirclePreview(e) {
        if (!isDrawing) return;

        context.clearRect(0, 0, canvas.width, canvas.height);
        const radius = Math.sqrt(Math.pow(e.offsetX - lastX, 2) + Math.pow(e.offsetY - lastY, 2));
        context.beginPath();
        context.arc(lastX, lastY, radius, 0, Math.PI * 2);
        context.stroke();
    }

    function drawCircleFinish(e) {
        if (!isDrawing) return;

        const radius = Math.sqrt(Math.pow(e.offsetX - lastX, 2) + Math.pow(e.offsetY - lastY, 2));
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.beginPath();
        context.arc(lastX, lastY, radius, 0, Math.PI * 2);
        context.stroke();
        stopDrawing();
        canvas.removeEventListener('mousemove', drawCirclePreview);
        canvas.removeEventListener('mouseup', drawCircleFinish);
        canvas.removeEventListener('mouseout', drawCircleFinish);
        canvas.addEventListener('mousedown', startDrawing);
        canvas.addEventListener('mousemove', draw);
        canvas.addEventListener('mouseup', stopDrawing);
        canvas.addEventListener('mouseout', stopDrawing);
    }

    function undo() {
        lines.pop();
        redraw();
    }

    function redo() {
        // 未実装
    }

    function clearCanvas() {
        context.clearRect(0, 0, canvas.width, canvas.height);
        lines = [];
    }

    function redraw() {
        clearCanvas();
        lines.forEach(line => {
            context.strokeStyle = line.color;
            context.lineWidth = line.thickness;
            context.beginPath();
            context.moveTo(line.points[0].x, line.points[0].y);
            line.points.forEach(point => context.lineTo(point.x, point.y));
            context.stroke();
        });
    }

    canvas.addEventListener('mousedown', startDrawing);
    canvas.addEventListener('mousemove', draw);
    canvas.addEventListener('mouseup', stopDrawing);
    canvas.addEventListener('mouseout', stopDrawing);

    document.getElementById('colorPicker').addEventListener('change', changeColor);
    document.getElementById('thickness').addEventListener('input', changeThickness);
    document.getElementById('pencil').addEventListener('click', toggleEraser);
    document.getElementById('line').addEventListener('click', drawLine);
    document.getElementById('rectangle').addEventListener('click', drawRectangle);
    document.getElementById('circle').addEventListener('click', drawCircle);
    document.getElementById('undo').addEventListener('click', undo);
    document.getElementById('redo').addEventListener('click', redo);
    document.getElementById('clear').addEventListener('click', clearCanvas);
</script>
</body>
</html>

Javascipt submitイベント

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My JavaScript</title>
</head>
<body>
  <form>
    <input type="text">
    <button>OK</button>
  </form>
  <p></p>
  
  <script src="main.js"></script>
</body>
</html>

main.js

'use strict';

{
  document.querySelector('form').addEventListener('submit', (e) => {
    e.preventDefault();
    document.querySelector('p').textContent = document.querySelector('input').value;
  });
}

Javascript mousemoveイベント

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My JavaScript</title>
</head>
<body>
  <p></p>
  
  <script src="main.js"></script>
</body>
</html>

main.js

'use strict';

{
  document.addEventListener('mousemove', (e) => {
    document.querySelector('p').textContent = `X: ${e.clientX} Y: ${e.clientY}`;
  });
}

python chatGPT2-AI

chatGPT-2.py

from flask import Flask, render_template, request, redirect, url_for
from transformers import GPT2Tokenizer, GPT2LMHeadModel
import wikipedia

app = Flask(__name__)

# GPT-2のトークナイザーとモデルをロード
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
model = GPT2LMHeadModel.from_pretrained("gpt2")

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/generate', methods=['POST'])
def generate_text():
    # ユーザーからの入力を取得
    prompt_text = request.form['prompt']
    
    try:
        # Wikipediaからテキストを取得
        wikipedia_text = wikipedia.summary(prompt_text)
        
        # テキストの生成
        inputs = tokenizer.encode(wikipedia_text, return_tensors="pt")
        outputs = model.generate(inputs, max_length=100, num_return_sequences=1, temperature=0.7)
        
        # 生成されたテキストをデコードしてHTMLコードに組み込む
        generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
        
        # 生成されたテキストとWikipediaのテキストと共にHTMLを返す
        return render_template('index.html', prompt_text=prompt_text, generated_text=generated_text, wikipedia_text=wikipedia_text)
    
    except wikipedia.exceptions.DisambiguationError as e:
        # 曖昧性がある場合は、候補のリストを表示
        options = e.options
        return render_template('disambiguation.html', options=options)
    
    except wikipedia.exceptions.PageError:
        wikipedia_text = "Wikipediaにそのトピックが見つかりませんでした。"
        return render_template('index.html', prompt_text=prompt_text, wikipedia_text=wikipedia_text)

@app.route('/generate_with_option/<option>', methods=['GET'])
def generate_with_option(option):
    try:
        # Wikipediaからテキストを取得
        wikipedia_text = wikipedia.summary(option)
        
        # テキストの生成
        inputs = tokenizer.encode(wikipedia_text, return_tensors="pt")
        outputs = model.generate(inputs, max_length=100, num_return_sequences=1, temperature=0.7)
        
        # 生成されたテキストをデコードしてHTMLコードに組み込む
        generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
        
        # 生成されたテキストとWikipediaのテキストと共にHTMLを返す
        return render_template('index.html', prompt_text=option, generated_text=generated_text, wikipedia_text=wikipedia_text)
    
    except wikipedia.exceptions.PageError:
        wikipedia_text = "Wikipediaにそのトピックが見つかりませんでした。"
        return render_template('index.html', prompt_text=option, wikipedia_text=wikipedia_text)

if __name__ == '__main__':
    app.run(debug=True)

templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generate Text</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }

        header {
            text-align: center;
            margin-top: 50px;
        }

        main {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        .form-section, .response-section, .wikipedia-section {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }

        .prompt-form {
            max-width: 100%;
        }

        label {
            font-weight: bold;
        }

        input[type="text"] {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            padding: 10px 20px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        button:hover {
            background-color: #0056b3;
        }

        .generated-text {
            margin-top: 20px;
        }

        .tweet-link {
            display: block;
            margin-top: 10px;
            text-align: center;
        }

        footer {
            text-align: center;
            margin-top: 50px;
        }
    </style>
</head>
<body>

    <header>
        <h1>Generate Text</h1>
    </header>

    <main>
        <section class="form-section">
            <form action="/generate" method="POST" class="prompt-form">
                <label for="prompt">Enter your prompt:</label><br>
                <input type="text" id="prompt" name="prompt" placeholder="Enter your prompt..."><br><br>
                <button type="submit">Generate</button>
            </form>
        </section>

        <!-- 生成されたテキストを表示 -->
        {% if generated_text %}
        <section class="response-section">
            <div class="response">
                <h2>Generated Text:</h2>
                <p class="generated-text">{{ generated_text }}</p>
                <a href="https://twitter.com/intent/tweet?text={{ generated_text }}" class="tweet-link">Tweet</a>
            </div>
        </section>
        {% endif %}

        <!-- Wikipediaからの関連情報を表示 -->
        {% if wikipedia_text %}
        <section class="wikipedia-section">
            <div class="wikipedia-info">
                <h2>Wikipedia Info:</h2>
                <p>{{ wikipedia_text }}</p>
            </div>
        </section>
        {% endif %}

        <!-- 保存ボタン -->
        <button id="saveButton">Save Generated Text</button>
    </main>

    <footer>
        <p>© 2024 Generate Text App</p>
    </footer>

    <script>
        // 保存ボタンがクリックされたときの処理
        document.getElementById('saveButton').addEventListener('click', function() {
            // 生成されたテキストを取得
            var generatedText = document.querySelector('.generated-text').innerText;
            // テキストをダウンロード用にBlobに変換
            var blob = new Blob([generatedText], { type: 'text/plain' });
            // BlobをURLに変換
            var url = window.URL.createObjectURL(blob);
            // ダウンロード用のリンクを作成してクリック
            var a = document.createElement('a');
            a.href = url;
            a.download = 'generated_text.txt';
            document.body.appendChild(a);
            a.click();
            // 不要なURLを解放
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        });
    </script>

</body>
</html>

今回はテキストデータを保存できるようにしました

Javascript Input

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My JavaScript</title>
</head>
<body>
  <input type="text">
  <p></p>
  
  <script src="main.js"></script>
</body>
</html>

main.js

'use strict';

{
  // input → text, textarea, select
  // change → radio, checkbox
  document.querySelector('input').addEventListener('input', () => {
    const pElement = document.querySelector('p');
    const inputElement = document.querySelector('input');
    // pElement.textContent = inputElement.value;
    pElement.textContent = inputElement.value.length;
  });
}