オレオレLiveViewCanvasを作る

LiveViewでCanvasで遊びたいと思いました
オレオレライブラリーを作りたいと思います

# hooks(JavaScriptの部分)

hooksを登録する
```diff_javascript:assets/js/app.js
// We import the CSS which is extracted to its own file by esbuild.
// Remove this line if you add a your own CSS build pipeline (e.g postcss).
import "../css/app.css"

// If you want to use Phoenix channels, run `mix help phx.gen.channel`
// to get started and then uncomment the line below.
// import "./user_socket.js"

// You can include dependencies in two ways.
//
// The simplest option is to put them in assets/vendor and
// import them using relative paths:
//
//     import "../vendor/some-package.js"
//
// Alternatively, you can `npm install some-package --prefix assets` and import
// them using a path starting with the package name:
//
//     import "some-package"
//

// Include phoenix_html to handle method=PUT/DELETE in forms and buttons.
import "phoenix_html"
// Establish Phoenix Socket and LiveView configuration.
import {Socket} from "phoenix"
import {LiveSocket} from "phoenix_live_view"
import topbar from "../vendor/topbar"
+ import {hooks} from "./render_hooks"

let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
- let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}})
+ let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}, hooks})

// Show progress bar on live navigation and form submits
topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"})
window.addEventListener("phx:page-loading-start", info => topbar.show())
window.addEventListener("phx:page-loading-stop", info => topbar.hide())

// connect if there are any LiveViews on the page
liveSocket.connect()

// expose liveSocket on window for web console debug logs and latency simulation:
// >> liveSocket.enableDebug()
// >> liveSocket.enableLatencySim(1000)  // enabled for duration of browser session
// >> liveSocket.disableLatencySim()
window.liveSocket = liveSocket

```

hooksファイルを作る
```javascript:新規作成 assets/js/render_hooks.js
export const hooks = {
    canvas: {
        mounted() {
            console.log("mount_hooks");
            render(JSON.parse(this.el.dataset.canvas));
        },
        updated() {
            console.log("update_hooks");
            render(JSON.parse(this.el.dataset.canvas));
        }
    }
}

const render = (datas) => {
    const canvas = document.querySelector('canvas');
    const ctx = canvas.getContext('2d');
    datas.map(data => render_exec(ctx, data));    
  }

const render_exec = (ctx, data) => {
    switch (data.fn) {
        case "fillRect":
            ctx.fillRect(data.x, data.y, data.w, data.h);
            break;
        case 'fillStyle':
            ctx.fillStyle = data.style;
            break;
        case 'strokeStyle':
            ctx.strokeStyle = data.style;
            break;
        case 'beginPath':
            ctx.beginPath();
            break;
        case 'stroke':
            ctx.stroke();
            break;
        case 'arc':
            ctx.arc(data.x, data.y, data.radius, data.start_angle, data.end_angle)
            break;
        case "moveTo":
            ctx.moveTo(data.x, data.y);
            break;
        case "lineTo":
            ctx.lineTo(data.x, data.y);
            break;
        default:
            console.log("no function");
    }
}
```

# hooksとやり取りするためのElixir側の関数
```Elixir:新規作成 lib/ymn_canvas/draw.ex
defmodule YmnCanvas.Draw do
  @doc """
  四角で塗りつぶす
  """
  def fill_rect(x, y, w, h) do
    %{
      fn: "fillRect",
      x: x,
      y: y,
      w: w,
      h: h
    }
  end

  @doc """
  塗りつぶす色を指定する
  """
  def fill_style(style) do
    %{
      fn: "fillStyle",
      style: style
    }
  end

  def stroke_style(style) do
    %{
      fn: "strokeStyle",
      style: style
    }
  end

  def begin_path() do
    %{
      fn: "beginPath"
    }
  end

  def stroke() do
    %{
      fn: "stroke"
    }
  end

  def arc(x, y, radius, start_angle, end_angle) do
    %{
      fn: "arc",
      x: x,
      y: y,
      radius: radius,
      start_angle: start_angle,
      end_angle: end_angle
    }
  end

  def move_to(x, y) do
    %{
      fn: "moveTo",
      x: x,
      y: y,
    }
  end

  def line_to(x, y) do
    %{
      fn: "lineTo",
      x: x,
      y: y,
    }
  end

end
```

# Liveviewコンポーネント

```elixir:新規作成 lib/ymn_canvas_web/live/components/canvas_component.ex
defmodule YmnCanvasWeb.CanvasComponent do
  use Phoenix.LiveComponent

  def render(assigns) do
    ~H"""
    <div id="canvas_div" phx-hook="canvas" data-canvas={Jason.encode!(@data)}>
      <canvas id="canvas_area"  width="1024" height="768">
      </canvas>
    </div>
    """
  end
end
```

# ルータの設定&実験用のページを作る

```diff_elixir:lib/ymn_canvas_web/router.ex
defmodule YmnCanvasWeb.Router do
  use YmnCanvasWeb, :router

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_live_flash
    plug :put_root_layout, {YmnCanvasWeb.LayoutView, :root}
    plug :protect_from_forgery
    plug :put_secure_browser_headers
  end

  pipeline :api do
    plug :accepts, ["json"]
  end

  scope "/", YmnCanvasWeb do
    pipe_through :browser

+   live "/", CanvasLive.Index, :index
  end

  # Other scopes may use custom stacks.
  # scope "/api", YmnCanvasWeb do
  #   pipe_through :api
  # end

  # Enables LiveDashboard only for development
  #
  # If you want to use the LiveDashboard in production, you should put
  # it behind authentication and allow only admins to access it.
  # If your application does not have an admins-only section yet,
  # you can use Plug.BasicAuth to set up some basic authentication
  # as long as you are also using SSL (which you should anyway).
  if Mix.env() in [:dev, :test] do
    import Phoenix.LiveDashboard.Router

    scope "/" do
      pipe_through :browser

      live_dashboard "/dashboard", metrics: YmnCanvasWeb.Telemetry
    end
  end

  # Enables the Swoosh mailbox preview in development.
  #
  # Note that preview only shows emails that were sent by the same
  # node running the Phoenix server.
  if Mix.env() == :dev do
    scope "/dev" do
      pipe_through :browser

      forward "/mailbox", Plug.Swoosh.MailboxPreview
    end
  end
end
```


```elixir:新規作成  lib/ymn_canvas_web/live/canvas_live/index.ex
defmodule YmnCanvasWeb.CanvasLive.Index do
  use YmnCanvasWeb, :live_view
  import YmnCanvas.Draw

  @impl true
  def mount(_params, _session, socket) do
    Process.send_after(self(), :update, 100)

    {:ok,
     socket
     |> assign(data: create_data())}
  end

  @impl true
  def handle_info(:update, socket) do
    Process.send_after(self(), :update, 100)

    {:noreply,
     socket
     |> assign(data: create_data())}
  end

  def create_data() do
    [
      fill_style("#FFFFBB"),
      fill_rect(1, 1, 640, 480),
      fill_style("#FFFFDD"),
      fill_rect(10, 10, 620, 460),
      stroke_style("red"),
      begin_path(),
      arc(300, 200, 100, 0, 2 * :math.pi()),
      move_to(0, 0),
      line_to(100, 100),
      move_to(400, 400),
      line_to(500, 300),
      stroke()
    ]
  end
end
```

```elixir:新規作成 lib/ymn_canvas_web/live/canvas_live/index.html.heex
<.live_component module={YmnCanvasWeb.CanvasComponent} id="hero" data={@data} />
```

# 実行結果
![Screenshot from 2023-02-04 20-36-23.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/295814/b63ebf28-5e25-a0dc-7c3b-1dc36ad2049f.png)