Hello all! Here's today's script! I call it CFGL (Canvas Free Game Lib)
Here's the code:
Code: function initCFGL(){
if (!window.hasbeeninit){
document.body.style.overflow = "hidden";
window.spritenum = 0
window.hasbeeninit=1
}
}
function SpriteObj(id){
this.id = id;
this.element = document.getElementById(id);
this.moveTo = function(x,y){
this.element.style.top = y+"px";
this.element.style.left = x+"px";
}
this.setWidth = function(width){
this.element.style.width = width+"px";
}
this.setHeight = function(height){
this.element.style.height = height+"px";
}
this.onclick = function(eventType,func){
this.element.onclick = func(this);
}
this.onmousedown = function(func){
this.element.onmousedown = func(this);
}
this.onmouseup = function(func){
this.element.onmouseup = func(this);
}
this.onmouseover = function(func){
this.element.onmouseover = func(this);
}
this.draggable = function(cond){
setDraggable(this.id,cond);
}
this.setZIndex = function(index){
this.element.style.zIndex = index.toString();
}
}
var indexcounter = 0;
function setDraggable(id,cond){
element = document.getElementById(id);
if (cond == true){
element.addEventListener('mousedown', dragStart, false);
window.addEventListener('mouseup', dragStop, false);
imgs = element.getElementsByTagName("img");
for(i in imgs){
imgs[i].draggable = false
}
}else{
element.removeEventListener('mousedown', dragStart);
console.log("False")
}
}
function dragStop(e){
window.removeEventListener('mousemove', dragMove, true);
}
function dragStart(e){
window.div = e.target;
console.log(e.target)
window.div.style.zIndex = ++window.indexcounter;
window.addEventListener('mousemove', dragMove, true);
window.offsetleft = window.div.offsetLeft - e.clientX;
window.offsettop = window.div.offsetTop - e.clientY;
}
function dragMove(e){
window.div.style.position = 'absolute';
window.div.style.top = e.clientY + window.offsettop + 'px';
window.div.style.left = e.clientX + window.offsetleft + 'px';
}
function newSprite(imgsrc){
document.body.innerHTML += '<div id="sprite'+window.spritenum.toString()+'"></div>';
sprite = document.getElementById('sprite'+window.spritenum.toString())
sprite.style.position = "absolute";
sprite.style.backgroundImage = "url("+imgsrc+")"
sprite.style.backgroundSize = "100% 100%";
sprite.style.width = "200px";
sprite.style.height = "200px";
return new SpriteObj('sprite'+window.spritenum.toString());
}
function removeSprite(sprite){
document.body.removeChild(sprite.element);
return 0;
}
Here's an example of how to use it:
Code: initCFGL();
var Sprite = newSprite("image-src-here");
for (i=0,i<=100,i++){
Sprite.moveTo(i,i);
}
//this moves the sprite smoothly to (100,100)