JSFiddle - React, Tailwind, and code Playground
by Hooman Askari
HTML
<canvas id="canvas" height='637' width='932' ></canvas>
JavaScript
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var mouse = {x: 0, y: 0}; //make an object to hold mouse position
var startCoords = {x: 0, y: 0};
var last = {x: 0, y: 0};
var isDown = false;
var scale = 2;
var img = new Image(),
bmg = new Image();
img.src = "http://i.imgur.com/XB00ORw.jpg";
bmg.src = "http://i.imgur.com/REZGQ9g.jpg"
function render() {
'use strict';
ctx.beginPath();
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.arc(canvas.width/2, canvas.height/2, 250, 0, 6.28, false);
ctx.restore();
ctx.save();
ctx.drawImage(bmg, 0, 0,
bmg.width * scale, bmg.height * scale);
ctx.clip();
ctx.drawImage(img, 0, 0,
bmg.width * scale, bmg.height * scale);
ctx.closePath();
ctx.restore();
}
setInterval(render, 60);// set the animation into motion
canvas.onmousemove = function (e) {
'use strict';
var xVal = e.pageX - this.offsetLeft,
yVal = e.pageY - this.offsetTop;
mouse = {x: e.pageX,
y: e.pageY};
if (isDown) {
ctx.setTransform(1, 0, 0, 1,
xVal - startCoords.x,
yVal - startCoords.y);
}
};
canvas.onmousedown = function (e) {
'use strict';
isDown = true;
startCoords = {x: e.pageX - this.offsetLeft - last.x,
y: e.pageY - this.offsetTop - last.y};
};
canvas.onmouseup = function (e) {
'use strict';
isDown = false;
last = {x: e.pageX - this.offsetLeft - startCoords.x,
y: e.pageY - this.offsetTop - startCoords.y};
};