JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="myCanvas" width="400" height="400" >
Your browser does not support the HTML5 canvas tag.
</canvas>
<p>Image reference:</p>
<img id="scream" src="http://www.w3schools.com/tags/img_the_scream.jpg" alt="The Scream">
CSS
canvas { border: 1px solid black; }
JavaScript
"use strict";
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var img = document.getElementById("scream");
function drawStuff() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// params: image, destinationX, destinationY
ctx.drawImage(img, 50, 50);
// params: image, destinationX, destinationY,
// destinationWidth, destinationHeight
ctx.drawImage(img, 300, 50, 80, 200);
}
function updateMousePos(evt) {
var x = evt.clientX - canvas.offsetLeft;
var y = evt.clientY - canvas.offsetTop;
drawStuff();
// params: image,
// sourceX, sourceY, sourceWidth, sourceHeight,
// destX, destY, destWidth, destHeight,
ctx.drawImage(img,
80, 100, 100, 160,
x, y, 50, 80);
}
drawStuff();
window.addEventListener("mousemove", updateMousePos);
console.log("Done!");