Skip to content

Instantly share code, notes, and snippets.

@krzykamil
Created February 13, 2023 09:40
Show Gist options
  • Save krzykamil/12c758bdd845d98887b2befedef60826 to your computer and use it in GitHub Desktop.
Save krzykamil/12c758bdd845d98887b2befedef60826 to your computer and use it in GitHub Desktop.
Drawing
<div data-controller="drawing" class="mt-4 p-6">
<h1>Drawing Lines</h1>
<button
class="my-4 mx-4 px-3 py-2 bg-red-600 font-semibold rounded"
data-action="drawing#drawLine"
data-drawing-length-param="300"
data-drawing-direction-param="horizontal"
data-drawing-x-param="100"
data-drawing-y-param="100"
>
Draw Horizontal Long
</button>
<button
class="my-4 mx-4 px-3 py-2 bg-red-600 font-semibold rounded"
data-action="drawing#drawLine"
data-drawing-length-param="100"
data-drawing-direction-param="horizontal"
data-drawing-x-param="200"
data-drawing-y-param="150"
>
Draw Horizontal Short
</button>
<button
class="my-4 mx-4 px-3 py-2 bg-orange-400 font-semibold rounded"
data-action="drawing#drawLine"
data-drawing-length-param="300"
data-drawing-direction-param="vertical"
data-drawing-x-param="300"
data-drawing-y-param="100"
>
Draw Vertical Long
</button>
<button
class="my-4 mx-4 px-3 py-2 bg-orange-400 font-semibold rounded"
data-action="drawing#drawLine"
data-drawing-length-param="100"
data-drawing-direction-param="vertical"
data-drawing-x-param="400"
data-drawing-y-param="200"
>
Draw Vertical Short
</button>
<canvas data-drawing-target="canvas" id="canvas" height="400" width="500"></canvas>
</div>
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets =["canvas", "roof"]
drawingContext;
connect() {
this.drawingContext = this.canvasTarget.getContext('2d')
this.drawingContext.strokeStyle = 'red';
this.drawingContext.lineWidth = 5;
}
drawLine(event) {
console.log(event.params)
this.drawingContext.beginPath();
this.drawingContext.moveTo(event.params.x, event.params.y);
if (event.params.direction === 'horizontal') {
this.drawingContext.lineTo(event.params.length, event.params.y);
} else {
this.drawingContext.lineTo(event.params.x, event.params.length);
}
this.drawingContext.lineTo(event.params.x, event.params.lengthY);
this.drawingContext.stroke();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment