I want to use a sprite in an html5 canvas context.
i want to drag it with my mouse.. so the displayed area changes while dragging the mouse.
It should look like a window with width: 21 and height: 90, where just a part of the sprite is visible. when i drag the sprite downwards or upwards i want the visible part to change.
I thought i can do this with the drawImage (slice) method, but it doesnt work how i want…
Can you please help me out?
<html>
<head>
<script type="text/javascript">
var y = 30;
var canvas;
var context;
var imageHours;
function clearClock(context) {
context.clearRect(0, 0, 300, 500);
}
function init(){
canvas = document.getElementById("uhr");
context = canvas.getContext("2d");
imageHours = new Image();
imageHours.src = "07.png";
context.drawImage(imageHours, 0, y, 21, 90, 50, 50, 21, 90);
var down = false;
canvas.addEventListener('mousedown', function(event) { down = true; }, false);
canvas.addEventListener('mouseup', function() { down = false; }, false);
canvas.addEventListener('mousemove', function(event){
if(down){
if(event.layerY > 50 && event.layerY < 140){
y = event.layerY;
}
clearClock(context);
context.drawImage(imageHours, 0, y, 21, 90, 50, 50, 21, 90);
}
}, false);
}
</script>
</head>
<body onload="init();">
<canvas id="uhr" height="500px" width="300px"/>
</body>
</html>
Sprite:

EDIT: i added a comment to my mainPost. the reason why i am trying to acomplish this like that is.. that i dont want to use a library for this.. because i want to learn such stuff… using libraries doesnt help me with learning…
Your question is a little confusing. I think creating a fiddle next time would be a good idea, it helps people help you.
I think this is what you are trying to do -> jsFiddle
Two issues I spotted:
Edit:
I’ve updated the fiddle here, this should be what you want and a good starting point for your app. I’d encourage you to read up a bit more on canvas, especially on using images. The Mozzila Dev Network has a great intro to it, check it out for a detailed explanation for why this code works the way it does.
Hope this helps!