JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<canvas id="meu_canvas" width="900" height="500"></canvas>
<script>
//canvas e contexto
var canvas = document.getElementById('meu_canvas');
var contexto = canvas.getContext('2d');
var playpause;
var x = 0;
var desloc = 2;
var LARGURA = 100;
var ALTURA = 140;
var frame = 1;
var imagem = new Image();
imagem.src = "IMG/ScottSprite.png";
imagem.onload = function() {
contexto.drawImage(imagem, 0, 0, LARGURA, ALTURA, x, 20, LARGURA, ALTURA);
}
//Caixa de botoes(Contem 3x funcoes: Desenhar uma caixa com DOIS botoes)
boxButton();
window.requestAnimationFrame(playAnimation);
//Função de animação
function playAnimation() {
contexto.clearRect(0, 0, canvas.width, 445);
//Deslocar
x = (x + LARGURA + desloc > canvas.width ? 0 : x + desloc);
if (x % (LARGURA / 2) == 0)
frame = (frame > 4 ? 2 : frame + 1);
//Desenhar a imagem.
desenharImagem();
//Chamando o cliclo novamente
window.requestAnimationFrame(playAnimation);
}
function desenharImagem() {
contexto.clearRect(0, 0, canvas.width, 445);
contexto.setLineDash([4, 2]);
contexto.strokeRect(0, 0, canvas.width, canvas.height);
contexto.drawImage(imagem, frame * LARGURA, 0, LARGURA, ALTURA, x, canvas.height / 2, LARGURA, ALTURA);
}
function botaoPlay() {
contexto.beginPath();
contexto.fillStyle = "rgb(255,255,0)";
contexto.moveTo(430, 450);
contexto.lineTo(460, 465);
contexto.lineTo(430, 480);
contexto.lineTo(430, 450);
...
JavaScript
$(document).ready(function() {
$('#meu_canvas').click(clickCanvas);
});
function clickCanvas(e) {
try {
var clickedX = e.pageX - this.offsetLeft;
var clickedY = e.pageY - this.offsetTop;
if (clickedX >= 430 && clickedX <= 460 && clickedY >= 450 && clickedY <= 480) {
alert("Click PLAY!");
} else if (clickedX >= 470 && clickedX <= 505 && clickedY >= 450 && clickedY <= 480) {
alert("Click STOP!");
}
} catch(e) {
alert(e.message);
}
}