Created
July 10, 2017 11:31
-
-
Save pourmesomecode/a2f77dcb3fb6e1b25f543bdad5423d80 to your computer and use it in GitHub Desktop.
canvas drag
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var canvas; | |
var ctx; | |
var x = 75; | |
var y = 50; | |
var WIDTH = 400; | |
var HEIGHT = 300; | |
var dragok = false; | |
function rect(x,y,w,h) { | |
ctx.beginPath(); | |
ctx.rect(x,y,w,h); | |
ctx.closePath(); | |
ctx.fill(); | |
} | |
function clear() { | |
ctx.clearRect(0, 0, WIDTH, HEIGHT); | |
} | |
function init() { | |
canvas = document.getElementById("canvas"); | |
ctx = canvas.getContext("2d"); | |
return setInterval(draw, 10); | |
} | |
function draw() { | |
clear(); | |
ctx.fillStyle = "#FAF7F8"; | |
rect(0,0,WIDTH,HEIGHT); | |
ctx.fillStyle = "#444444"; | |
rect(x - 15, y - 15, 30, 30); | |
} | |
function myMove(e){ | |
if (dragok){ | |
x = e.pageX - canvas.offsetLeft; | |
y = e.pageY - canvas.offsetTop; | |
} | |
} | |
function myDown(e){ | |
x = e.pageX - canvas.offsetLeft; | |
y = e.pageY - canvas.offsetTop; | |
dragok = true; | |
canvas.onmousemove = myMove; | |
} | |
function myUp(){ | |
dragok = false; | |
canvas.onmousemove = null; | |
} | |
init(); | |
canvas.onmousedown = myDown; | |
canvas.onmouseup = myUp; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment