Selecting an Image in KineticJS - javascript

I have multiple images in Kineticjs stage. I have to get the properties of the image (x, y, height, width) on clicking on the image.

Here's an example of how to have a Kinetic.Image report it's XY when clicked.
preload all your images first
attach the click event to each new Kinetic.Image
Example code and a Demo: http://jsfiddle.net/m1erickson/58a89/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Prototype</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.0.1.min.js"></script>
<style>
body{padding:20px;}
#container{
border:solid 1px #ccc;
margin-top: 10px;
width:350px;
height:350px;
}
</style>
<script>
$(function(){
var stage = new Kinetic.Stage({
container: 'container',
width: 350,
height: 350
});
var layer = new Kinetic.Layer();
stage.add(layer);
// first fully load all images into imgs[]
// then call start() when all are loaded
var imageURLs=[]; // put the paths to your images here
var imagesOK=0;
var imgs=[];
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-1.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-2.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-3.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-4.jpg");
loadAllImages(start);
function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}
function start(){
// the imgs[] array holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
for(var i=0;i<imgs.length;i++){
addImage(imgs[i],i*60,10,50,50);
}
}
function addImage(img,x,y,w,h){
var image=new Kinetic.Image({
x:x,
y:y,
width:w,
height:h,
image:img,
draggable:true
});
image.on("click",function(){
var pos=this.position();
alert(parseInt(pos.x)+","+parseInt(pos.y));
});
layer.add(image);
layer.draw();
}
}); // end $(function(){});
</script>
</head>
<body>
<h4>Drag to new position. Click to get XY.</h4>
<div id="container"></div>
</body>
</html>

When you load the images, bind a click event :
imageObj.onload = function(){
var currentImg = new Kinetic.Image({
// define x,y,W and H
});
currentImg.on("click", function(e) {
//x position for example
console.log(currentImg.getPosition().x);
});
}

Related

HTML5 Canvas how to make image can resizable by Kinetic.js?

I have add image function :
$("ul#img a").click(function(){
addProduct( $('img', this) );
});
function addProduct( imgObj ){
var layer = new Kinetic.Layer();
var imageObj = new Image(); //createimage
imageObj.onload = function() {
var image = new Kinetic.Image({
x: stage.getWidth() / 2 - 53,
y: stage.getHeight() / 2 - 59,
image: imageObj,
draggable: true,
name: "image"
});
// add the shape to the layer
layer.add(image);
// add the layer to the stage
stage.add(layer);
=========== End function add Image to canvas ============
image.on("mouseover", function(){
var imagelayer = this.getLayer();
document.body.style.cursor = "move";
this.setStrokeWidth(2);
this.setStroke("white"); //It's border of image when hover
layer.draw();
writeMessage(messageLayer, "Delete it");}); //DeleteItem
image.on("mouseout", function(){
var imagelayer = this.getLayer();
document.body.style.cursor = "default";
this.setStrokeWidth(0);
this.setStroke("transparent");
layer.draw();
writeMessage(messageLayer, "");});
image.on("dblclick dbltap", function(){
layer.remove(image);
layer.clear();
layer.draw();});};
imageObj.src = imgObj.attr('src'); }
=========== End Event of Image ============
This code can add image to canvas ,can dragable but cant resizable
How to make this image can resizable?
Please explain to me please
Thank you so much.
Kinetic elements do not have a built-in way to let the user resize.
Here's code to let the user drag the right edge of the image to resize the image:
Listen for mousedown, mouseup and mousemove
If mousedown occurs on the right edge of the image, save that mouse x,y,
On each mousemove, scale the image by the aspect ratio created by the distance the mouse has moved.
Example code to get you started:
var stage = new Kinetic.Stage({
container: 'container',
width: 350,
height: 350
});
var layer = new Kinetic.Layer();
stage.add(layer);
var kImage;
var startRight=-1;
var startWidth=0;
var startHeight=0;
var img=new Image();
img.crossOrigin="anonymous";
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/facesSmall.png";
function start(){
kImage = new Kinetic.Image({
image:img,
x:10,
y:10,
width:img.width,
height:img.height,
});
layer.add(kImage);
layer.draw();
}
$(stage.getContent()).on('mousedown', function (event) {
var pos=stage.getPointerPosition();
var mouseX=parseInt(pos.x);
var mouseY=parseInt(pos.y);
var ipos=kImage.position();
var isize=kImage.getSize();
var right=ipos.x+isize.width;
if(mouseX>right-10 && mouseX<right+10){
startRight=mouseX;
startWidth=isize.width;
startHeight=isize.height;
}
});
$(stage.getContent()).on('mouseup', function (event) {
startRight=-1;
});
$(stage.getContent()).on('mousemove', function (event) {
if(startRight>=0){
var pos=stage.getPointerPosition();
var mouseX=parseInt(pos.x);
var mouseY=parseInt(pos.y);
var dx=mouseX-startRight;
var scaleFactor=(mouseX-(startRight-startWidth))/startWidth;
kImage.width(startWidth*scaleFactor);
kImage.height(startHeight*scaleFactor);
layer.draw();
}
});
body{padding:20px;}
#container{
border:solid 1px #ccc;
margin-top: 10px;
width:350px;
height:350px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/kineticjs/5.2.0/kinetic.js"></script>
<h4>Drag the right border of the image to resize<br>it while maintaining aspect ratio.</h4>
<div id="container"></div>

print copy of image when drag the original image

In jsfiddle.net/LuZbV/23/ i want, when dragging the image within the container i want to print a copy of image at perticular x,y coordinate and previous drawn image should be erase how can i do this?please help me...
JS Code
$(function(){
var $house=$("#house");
$house.hide();
var $stageContainer=$("#container");
var stageOffset=$stageContainer.offset();
var offsetX=stageOffset.left;
var offsetY=stageOffset.top;
var stage = new Kinetic.Stage({
container: 'container',
width: 350,
height: 350
});
var layer = new Kinetic.Layer();
stage.add(layer);
var image1=new Image();
image1.onload=function(){
$house.show();
}
image1.src="http://vignette1.wikia.nocookie.net/angrybirds/images/b/b6/Small.png/revision/latest?cb=20120501022157";
// make the toolbar image draggable
$house.draggable({
helper:'clone',
});
$house.data("url","house.png"); // key-value pair
$house.data("width","32"); // key-value pair
$house.data("height","33"); // key-value pair
$house.data("image",image1); // key-value pair
$stageContainer.droppable({
drop:dragDrop,
});
function dragDrop(e,ui){
var x=parseInt(ui.offset.left-offsetX);
var y=parseInt(ui.offset.top-offsetY);
var element=ui.draggable;
var data=element.data("url");
var theImage=element.data("image");
var image = new Kinetic.Image({
name:data,
x:x,
y:y,
image:theImage,
draggable: true,
dragBoundFunc: function(pos) {
return {
x: pos.x,
y: this.getAbsolutePosition().y
}
}
});
image.on("dragend", function() {
var points = image.getPosition();
//alert(points.x + ',' + points.y);
var image1 = new Kinetic.Image({
name: data,
id: "imageantry",
x: points.x+65,
y: points.y,
image: theImage,
draggable: false
});
layer.add(image1);
layer.draw();
});
image.on('dblclick', function() {
image.remove();
layer.draw();
});
layer.add(image);
layer.draw();
}
}); // end $(function(){});
HTML Code
<div id="toolbar">
<img id="house" width=32 height=32 src="http://vignette1.wikia.nocookie.net/angrybirds/images/b/b6/Small.png/revision/latest?cb=20120501022157"><br>
</div>
<div id="container"></div>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Prototype</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.2.min.js"> </script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<style>
body{padding:20px;}
#container{
border:solid 1px #ccc;
margin-top: 10px;
width:350px;
height:350px;
}
#toolbar{
width:350px;
height:35px;
border:solid 1px blue;
}
</style>
<script>
$(function(){
var $house=$("#house");
$house.hide();
var $stageContainer=$("#container");
var stageOffset=$stageContainer.offset();
var offsetX=stageOffset.left;
var offsetY=stageOffset.top;
var stage = new Kinetic.Stage({
container: 'container',
width: 350,
height: 350
});
var layer = new Kinetic.Layer();
stage.add(layer);
var image1=new Image();
image1.onload=function(){
$house.show();
}
image1.src="http://vignette1.wikia.nocookie.net/angrybirds/images/b/b6/Small.png/revision/latest?cb=20120501022157";
$house.draggable({
helper:'clone',
});
$house.data("url","house.png"); // key-value pair
$house.data("width","32"); // key-value pair
$house.data("height","33"); // key-value pair
$house.data("image",image1); // key-value pair
$stageContainer.droppable({
drop:dragDrop,
});
function dragDrop(e,ui){
var x=parseInt(ui.offset.left-offsetX);
var y=parseInt(ui.offset.top-offsetY);
var element=ui.draggable;
var data=element.data("url");
var theImage=element.data("image");
var image = new Kinetic.Image({
name:data,
x:x,
y:y,
image:theImage,
draggable: true,
dragBoundFunc: function(pos) {
return {
x: pos.x,
y: this.getAbsolutePosition().y
}
}
});
//get image position.
var w=0;
var obj;
image.on("dragend", function(e) {
w=w+1;
var points = image.getPosition();
if(w>1){
obj = stage.get('#imageantry')
obj.remove();
}
var image2 = new Kinetic.Image({
name: data,
id: "imageantry",
x: points.x+75,
y: points.y,
image: theImage,
draggable: false
});
layer.add(image2);
layer.draw();
});
image.on('dblclick', function() {
image.remove();
layer.draw();
});
layer.add(image);
layer.draw();
}
}); // end $(function(){});
</script>
</head>
<body>
<div id="toolbar">
<img id="house" width=32 height=32 src="http://vignette1.wikia.nocookie.net/angrybirds/images/b/b6/Small.png/revision/latest?cb=20120501022157"><br>
</div>
<div id="container"></div>
</body>
</html>

JavaScript is not sending the new value and not firing onload for first time

I am developing a web app that clients can upload image, I will find faces in that image and send back rectangles to client.
I am using ajaxfileupload function for saving image on server but for efficiency I am loading images from client computer and sending rectangles from server.
I am having two problem here:
1-)For the first image image.onload is not firing but its creating canvas and uploadHandler function its not calling.
2-)uploadHandler function is getting the same canvas for all images.Therefore its drawing my rectangles on the first image.
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script src="jquery.ajaxfileupload.js"></script>
<script src="ocanvas-2.7.2.min.js"></script>
<script type="text/javascript">
function uploadHandler(canvas)
{
$('input[type="file"]').ajaxfileupload({
'action': 'upload',
'onComplete': function(response) {
for (var i= 0; i < response.faces.length;i++)
{
var item = response.faces[i];
//alert("Tx:"+item.Tx+" Ty:"+item.Ty+" Bx:"+item.Bx+" By:"+item.By);
var rectangle = canvas.display.rectangle({
x: parseInt(item.Tx),
y: parseInt(item.Ty),
width: parseInt(parseInt(item.Bx)-parseInt(item.Tx)),
height: parseInt(parseInt(item.By)-parseInt(item.Ty)),
stroke: "5px #0aa"
});
canvas.addChild(rectangle);
}
},
'onStart': function() {
}
});
}
$(document).ready(function(){
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
var img = new Image();
img.onload = function(e) {
var elementID = 'canvas' + $('canvas').length; // Unique ID
//create canvas
$('<canvas>').attr({
id: elementID,
width: this.width + 'px',
height: this.height + 'px'
}).appendTo('#fileDisplayArea');
var canvas = oCanvas.create({
canvas: '#'+elementID
});
//add image to canvas
var image = canvas.display.image({
x: this.width,
y: this.height,
origin:{x:this.width,y:this.height},
image: reader.result
});
canvas.addChild(image);
//upload to server
uploadHandler(canvas);
}
img.src = reader.result;
//fileDisplayArea.appendChild(img);
}
reader.readAsDataURL(file);
} else {
fileDisplayArea.innerHTML = "File not supported!";
}
});
});
</script>
this is for 4 images
<input type="file" name="fileInput" id="fileInput"/>
<div id="upload" style="display: none;"></div>
<input id="predict" type="button" value="Process"></input>
<div id="work_place"></div>
<div id="fileDisplayArea">
<canvas id="canvas0" width="634px" height="471px"></canvas>
<canvas id="canvas1" width="600px" height="338px"></canvas>
<canvas id="canvas2" width="400px" height="400px"></canvas>
<canvas id="canvas3" width="960px" height="960px"></canvas>
</div>

Reduce radius of circle on mousemove kineticjs

I'm trying to create a html5 canvas painting application using kinetic.js where users can select various shapes and draw them on canvas .
When a user selects circle and tries to draw it , the radius of circle should depend on the distance the mouse has covered on the canvas , now the problem is when the radius of circle increase it works fine but when I decrease it the circle remain of same size .
It would be great if someone can point me to the right direction .
Here is the link to fiddle . http://jsfiddle.net/45fEn/
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div id="container"></div>
<script src="kinetic.js"></script>
<script src="js/jquery.js"></script>
<script defer="defer">
$(document).ready(function() {
var stage = new Kinetic.Stage({
container:'container',
width:300,
height:400
});
var layer = new Kinetic.Layer();
function drawCircle() {
var circle = new Kinetic.Circle({
x:initialX, y:initialY , radius:tangant , fill:'green'
});
layer.add(circle) ;
stage.add(layer);
}
stage.add(layer);
var painting =false , clicking = false ;
var initialX , initialY , finalX , finalY , tangant , newTangant ,storeTime;
$("canvas").mousedown(function(ev) {
initialX = ev.clientX;
initialY = ev.clientY;
painting = true;
clicking = true;
});
$("canvas").mousemove(function(ev) {
finalX = ev.clientX ;
finalY = ev.clientY ;
var diffX = initialX - finalX ;
var diffY = initialY - finalY ;
tangant = Math.sqrt ( Math.pow(diffX,2) + Math.pow(diffY,2) ) ;
console.log(tangant);
storeTime = setTimeout(function() { newTangant = tangant },200) ;
if(newTangant < tangant) { console.log("new tan:"+newTangant);
circle.remove();
drawCircle();
}
if(clicking == true) {
drawCircle();
}
});
$("canvas").mouseup(function(ev) {
painting = false;
clicking = false;
});
});
</script>
</body>
</html>
You’re close!
BTW, you can also use stage.getContent to hook into stage mouse events.
stage.getContent()).on('mousedown', function (event) { …do mousedown stuff… }
Instead of removing and recreating the circle...
...just use circle.setRadius(newRadius) to resize the existing circle.
$(stage.getContent()).on('mousemove', function (event) {
if(!isDragging){return;}
var pos=stage.getMousePosition();
var mouseX=parseInt(pos.x);
var mouseY=parseInt(pos.y);
var dx=mouseX-initialX;
var dy=mouseY-initialY;
var r=Math.sqrt(dx*dx+dy*dy);
// this will resize the circle that is currently being created/resized
draggedCircle.setRadius(r);
layer.draw();
});
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/KLcRc/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Prototype</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.0.min.js"></script>
<style>
#container{
border:solid 1px #ccc;
margin-top: 10px;
width:400px;
height:400px;
}
</style>
<script>
$(function(){
var stage = new Kinetic.Stage({
container: 'container',
width: 400,
height: 400
});
var layer = new Kinetic.Layer();
stage.add(layer);
var draggedCircle,initialX,initialY;
var radius=25;
var isDragging=false;
function newCircle(mouseX,mouseY){
initialX=mouseX;
initialY=mouseY;
var circle = new Kinetic.Circle({
x:initialX,
y:initialY ,
radius:1,
fill:'green'
});
layer.add(circle) ;
layer.draw();
return(circle);
}
$(stage.getContent()).on('mousedown', function (event) {
var pos=stage.getMousePosition();
var mouseX=parseInt(pos.x);
var mouseY=parseInt(pos.y);
draggedCircle=newCircle(mouseX,mouseY);
isDragging=true;
});
$(stage.getContent()).on('mousemove', function (event) {
if(!isDragging){return;}
var pos=stage.getMousePosition();
var mouseX=parseInt(pos.x);
var mouseY=parseInt(pos.y);
var dx=mouseX-initialX;
var dy=mouseY-initialY;
var r=Math.sqrt(dx*dx+dy*dy);
draggedCircle.setRadius(r);
layer.draw();
});
$(stage.getContent()).on('mouseup', function (event) {
isDragging=false;
});
}); // end $(function(){});
</script>
</head>
<body>
<p>Drag to create a resizable circle</p>
<div id="container"></div>
</body>
</html>

Using HTML5 Canvas to parse an image into a tileset

I'm attempting to parse a tileset image (of type .png) into an array. I've got a test canvas that I'm using to draw it to first, then I am extracting the image info from it. When I run this code, it throws "Uncaught TypeError: Type error." I was able to log that this.mainTiles is empty. Any ideas? I don't know all the subtleties of Canvas yet, so I'm stuck. Thanks for the help! (Also, you can ignore the last line at the end, I was just using it to test--but I wanted to illustrate that it doesn't work).
function TileSet() {
this.tileSheets = [];
this.mainTiles = [];
this.tileHeight = 32;
this.tileWidth = 32;
this.addSpriteSheet = function (spriteSheetLoc, name) {
var tileSheet = new Image();
try {
tileSheet.src = spriteSheetLoc;
}
catch(err) {
dMode.Log("Invalid TileSheet Src ( TileSet.setSpriteSheet() Failed ); ERR: " + err);
}
tempContext.drawImage(tileSheet, 0, 0);
var tilesX = tempContext.width / this.tileWidth;
var tilesY = tempContext.height / this.tileHeight;
for(var i=0; i<tilesY; i++) {
for(var j=0; j<tilesX; j++) {
// Store the image data of each tile in the array.
this.mainTiles.push(tempContext.getImageData(j*this.tileWidth, i*this.tileHeight, this.tileWidth, this.tileHeight));
}
}
context.putImageData(this.mainTiles[0], 5, 5);
}
Edit: Here are how the canvases and such are defined:
var tempCanvas = document.getElementById("tempCanvas");
var tempContext = tempCanvas.getContext("2d");
var canvas = document.getElementById("gameCanvas");
var context = canvas.getContext("2d");
var Tiles = new TileSet;
//this is the line it gets stuck at
Tiles.addSpriteSheet("resources/tiles/tilea2.png");
Edit 2: After markE's answer, here's the latest update. Still feel as though I'm missing a fundamental property regarding .onload.
function TileSet() {
this.Tiles = [];
this.tileHeight = 32;
this.tileWidth = 32;
this.tileCount = 4;
this.addSpriteSheet = function (spriteSheetLoc, name) {
var tileSheet = new Image();
tileSheet.onload = function() {
tempCanvas.width = tileSheet.width;
tempCanvas.height = tileSheet.height;
tempContext.drawImage(tileSheet, 0, 0);
for (var t=0;t<this.tileCount;t++) {
this.Tiles[t]=tempContext.getImageData(t*this.tileWidth,t*32,this.tileWidth,tileSheet.height);
dMode.Log(this.Tiles);
}
context.putImageData(this.Tiles[this.Tiles.length-1],0,0);
dMode.Log(this.Tiles);
}
tileSheet.src = spriteSheetLoc;
}
Here's how to parse a spritesheet into an array of separate canvas imageData
I have some working code that does what you want to do.
I didn't have your "resources/tiles/tilea2.png" so I used my own "monstersArun.png" which is a 10 across spritesheet of 64x64 tiles.
You can modify this code to fit your spritesheet layout ( rows x columns and tile size).
Here is the code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var tileCount=10;
var tiles=new Array();
var tileWidth;
var t;
var img=new Image();
img.onload=function(){
canvas.width=img.width;
canvas.height=img.height;
tileWidth=img.width/tileCount;
ctx.drawImage(img,0,0);
for(var t=0;t<tileCount;t++){
tiles[t]=ctx.getImageData(t*tileWidth,0,tileWidth,img.height);
}
// just a test
// draw the last tiles[] into another canvas
var canvasTile=document.getElementById("canvasTile");
var ctxTile=canvasTile.getContext("2d");
canvasTile.width=tileWidth;
canvasTile.height=canvas.height;
ctxTile.putImageData(tiles[tiles.length-1],0,0);
}
img.src="monsterarun.png";
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas><br/>
<canvas id="canvasTile" width=64 height=64></canvas>
</body>
</html>
[Edit--to include Juan Mendes good idea give help on coding problem]
Also, as I look at your code...here:
tileSheet.src = spriteSheetLoc;
This causes your image to load. That loading takes time to do, so javascript starts loading the image, but it also immediately goes on to your next line of code. As a result, your code below tries to use the image before it's available--no good!
So you should give javascript a chance to fully load your image before processing the rest of your code. You do this using the onload method of Image like this:
var tileSheet = new Image();
tileSheet.onload=function(){
// put ALL you code that depends on the image being fully loaded here
}
tileSheet.src = spriteSheetLoc;
Notice how you put tileSheet.src after the onload function. In reality, javascript executes tilesheet.src and then goes back to execute all the code in the onload block!
[Edit again -- complete code]
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var tempCanvas = document.getElementById("tempCanvas");
var tempContext = tempCanvas.getContext("2d");
var canvas = document.getElementById("gameCanvas");
var context = canvas.getContext("2d");
// create a new TileSet
var Tiles = new TileSet();
// parse a spritesheet into tiles
//Tiles.addSpriteSheet("resources/tiles/tilea2.png","anyName");
Tiles.addSpriteSheet("houseIcon.png","anyName");
function TileSet() {
this.Tiles = [];
this.tileHeight = 32;
this.tileWidth = 32;
this.tileCount = 4;
this.addSpriteSheet = function (spriteSheetLoc, name) {
var me=this; // me==this==TileSet
var tileSheet = new Image();
tileSheet.onload = function() {
// calculate the rows/cols in the spritesheet
// tilesX=rows, tilesY=cols
var tilesX = tileSheet.width / me.tileWidth;
var tilesY = tileSheet.height / me.tileHeight;
// set the spritesheet canvas to spritesheet.png size
// then draw spritesheet.png into the canvas
tempCanvas.width = tileSheet.width;
tempCanvas.height = tileSheet.height;
tempContext.drawImage(tileSheet, 0, 0);
for(var i=0; i<tilesY; i++) {
for(var j=0; j<tilesX; j++) {
// Store the image data of each tile in the array.
me.Tiles.push(tempContext.getImageData(j*me.tileWidth, i*me.tileHeight, me.tileWidth, me.tileHeight));
}
}
// this is just a test
// display the last tile in a canvas
context.putImageData(me.Tiles[me.Tiles.length-1],0,0);
}
// load the spritesheet .png into tileSheet Image()
tileSheet.src = spriteSheetLoc;
}
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="tempCanvas" width=300 height=300></canvas><br/>
<canvas id="gameCanvas" width=300 height=300></canvas>
</body>
</html>
Try replacing tempContext.width and tempContext.height with tempCanvas.width and tempCanvas.height, respectively. I don't believe contexts have width/height.

Categories

Resources