Canvas for image clipping - context.drawImage() - javascript

I want to show four canvas from the same image
I'm working with an image which I need to be splitted into four pieces. I don't know the actual dimensions of the image so I need it to be dynamic. I already get this far, and I think the first piece is working fine, but I don't know why it is not working for the rest of the pieces. Could you point where the error could be?
I am new working with canvas, so my code is based on this answer:
https://stackoverflow.com/a/8913024/6929416
var image = new Image();
image.crossOrigin = 'anonymous';
image.src = 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png';
image.onload = cutImageUp;
function cutImageUp() {
var natW = image.width / 2;
var natH = image.height / 2;
var widthOfOnePiece = jQuery(window).width() / 2;
var heightOfOnePiece = jQuery(window).height() / 2;
var imagePieces = [];
for (var x = 0; x < 2; ++x) {
for (var y = 0; y < 2; ++y) {
var canvas = document.createElement('canvas');
canvas.width = widthOfOnePiece;
canvas.height = heightOfOnePiece;
var context = canvas.getContext('2d');
context.drawImage(image,
x * natW, y * natH,
natW, natH,
x * canvas.width, y * canvas.height,
canvas.width, canvas.height
);
/*drawImage(image,
sx, sy,
sWidth, sHeight,
dx, dy,
dWidth, dHeight);*/
imagePieces.push(canvas.toDataURL());
}
}
// imagePieces now contains data urls of all the pieces of the image
// load one piece onto the page
var anImageElement = document.getElementById('testing');
var anImageElement2 = document.getElementById('testing2');
var anImageElement3 = document.getElementById('testing3');
var anImageElement4 = document.getElementById('testing4');
anImageElement.src = imagePieces[0];
anImageElement2.src = imagePieces[1];
anImageElement3.src = imagePieces[2];
anImageElement4.src = imagePieces[3];
}
img{ border: 1px solid; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<img id="testing" src="">
<img id="testing2" src="">
<img id="testing3" src="">
<img id="testing4" src="">
</section>
I expect the canvas dimensions to fit on the screen, so I set them to half of the windows width and height.

The parameters for drawImage are
drawImage(
source,
sourceX, sourceY, sourceWidth, sourceHeight,
destinationX, destinationY, destinationWidth, destinationHeight
)
In your code, you are setting destinationX to x * canvas.width and destinationY to y * canvas.height. This means that for every iteration where either x or y are not 0, you are drawing outside of the destination area, that is for every parts but the first one.
Simply hard-code destinationX-Y to 0and you'll be good.
var image = new Image();
image.crossOrigin = 'anonymous';
image.src = 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png';
image.onload = cutImageUp;
function cutImageUp() {
var natW = image.width / 2;
var natH = image.height / 2;
var widthOfOnePiece = jQuery(window).width() / 2;
var heightOfOnePiece = jQuery(window).height() / 2;
var imagePieces = [];
for (var x = 0; x < 2; ++x) {
for (var y = 0; y < 2; ++y) {
var canvas = document.createElement('canvas');
canvas.width = widthOfOnePiece;
canvas.height = heightOfOnePiece;
var context = canvas.getContext('2d');
context.drawImage(image,
x * natW, y * natH,
natW, natH,
0, 0,
canvas.width, canvas.height
);
/*drawImage(image,
sx, sy,
sWidth, sHeight,
dx, dy,
dWidth, dHeight);*/
imagePieces.push(canvas.toDataURL());
}
}
// imagePieces now contains data urls of all the pieces of the image
// load one piece onto the page
var anImageElement = document.getElementById('testing');
var anImageElement2 = document.getElementById('testing2');
var anImageElement3 = document.getElementById('testing3');
var anImageElement4 = document.getElementById('testing4');
anImageElement.src = imagePieces[0];
anImageElement2.src = imagePieces[1];
anImageElement3.src = imagePieces[2];
anImageElement4.src = imagePieces[3];
}
img{ border: 1px solid; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<img id="testing" src="">
<img id="testing2" src="">
<img id="testing3" src="">
<img id="testing4" src="">
</section>
But note that toDataURL should almost never be used. Instead one should always prefer faster non-blocking and memory friendly toBlob().
Also, no need to create 4 canvases here, you can reuse the same at every round.
And finally, you might want to preserve your image's aspect ratio:
var image = new Image();
image.crossOrigin = 'anonymous';
image.src = 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png';
image.onload = cutImageUp;
function cutImageUp() {
var natW = image.width / 2;
var natH = image.height / 2;
var widthOfOnePiece = jQuery(window).width() / 2 - 20;
// preserve aspect ratio
var heightOfOnePiece = widthOfOnePiece * (natH / natW);
var canvas = document.createElement('canvas');
canvas.width = widthOfOnePiece;
canvas.height = heightOfOnePiece;
var context = canvas.getContext('2d');
var promises = [];
for (var y = 0; y < 2; ++y) {
for (var x = 0; x < 2; ++x) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(image,
x * natW, y * natH,
natW, natH,
0, 0,
canvas.width, canvas.height
);
promises.push(new Promise(function(resolve, reject) {
canvas.toBlob(function(blob) {
if (!blob) reject();
resolve(blob);
});
}));
}
}
return Promise.all(promises).then(function(blobs) {
// imagePieces now contains data urls of all the pieces of the image
// load one piece onto the page
var anImageElement = document.getElementById('testing');
var anImageElement2 = document.getElementById('testing2');
var anImageElement3 = document.getElementById('testing3');
var anImageElement4 = document.getElementById('testing4');
anImageElement.src = URL.createObjectURL(blobs[0]);
anImageElement2.src = URL.createObjectURL(blobs[1]);
anImageElement3.src = URL.createObjectURL(blobs[2]);
anImageElement4.src = URL.createObjectURL(blobs[3]);
})
}
img {
border: 1px solid;
display: inline-block;
}
body{margin: 0;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<img id="testing" src="">
<img id="testing2" src="">
<img id="testing3" src="">
<img id="testing4" src="">
</section>

Related

how to draw contour around text image

How can i generate outline effect on text image in java script?
The closest solution on StackOverflow I found is How to add stroke/outline to transparent PNG image in JavaScript canvas
I have tried this code but it is working fine in any shape
But my requirement is to draw outline like below images for example
// canvas related variables
var canvas = document.getElementById("canvas");
// canvas.width = 600;
// canvas.height = 400;
var ctx = canvas.getContext("2d");
// variables used in pixel manipulation
var canvases = [];
var imageData, data, imageData1, data1;
// size of sticker outline
var strokeWeight = 8;
// true/false function used by the edge detection method
var defineNonTransparent = function(x, y) {
return (data1[(y * cw + x) * 4 + 3] > 0);
}
var img = new Image();
document.querySelector('#fileinput').addEventListener('change', function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(event) {
let innerImageURL = event.target.result;
console.log(innerImageURL);
img = new Image();
img.crossOrigin = "anonymous";
img.onload = start;
img.src = innerImageURL;
// img.src = "https://cdn.glitch.com/c3106e6c-98cb-40e4-b0c1-85257680d25a%2Fsun.png?v=1564472507237";
};
reader.readAsDataURL(file);
});
// the image receiving the sticker effect
// var img = new Image();
// img.crossOrigin = "anonymous";
// img.onload = start;
// img.src = "https://cdn.glitch.com/c3106e6c-98cb-40e4-b0c1-85257680d25a%2Fsun.png?v=1564472507237";
function start() {
console.log(img.width)
console.log(img.height)
// resize the main canvas to the image size
canvas.width = cw = img.width;
canvas.height = ch = img.height;
// draw the image on the main canvas
ctx.drawImage(img, 0, 0);
// Move every discrete element from the main canvas to a separate canvas
// The sticker effect is applied individually to each discrete element and
// is done on a separate canvas for each discrete element
while (moveDiscreteElementToNewCanvas()) {}
// add the sticker effect to all discrete elements (each canvas)
for (var i = 0; i < canvases.length; i++) {
addStickerEffect(canvases[i], strokeWeight);
ctx.drawImage(canvases[i], 0, 0);
}
// redraw the original image
// (necessary because the sticker effect
// slightly intrudes on the discrete elements)
ctx.drawImage(img, 0, 0);
}
//
function addStickerEffect(canvas, strokeWeight) {
var url = canvas.toDataURL();
var ctx1 = canvas.getContext("2d");
var pts = canvas.outlinePoints;
addStickerLayer(ctx1, pts, strokeWeight);
var imgx = new Image();
imgx.onload = function() {
ctx1.drawImage(imgx, 0, 0);
}
imgx.src = url;
}
function addStickerLayer(context, points, weight) {
imageData = context.getImageData(0, 0, canvas.width, canvas.height);
data1 = imageData.data;
var points = geom.contour(defineNonTransparent);
defineGeomPath(context, points)
context.lineJoin = "round";
context.lineCap = "round";
context.strokeStyle = "white";
context.lineWidth = weight;
context.stroke();
}
// This function finds discrete elements on the image
// (discrete elements == a group of pixels not touching
// another groups of pixels--e.g. each individual sprite on
// a spritesheet is a discreet element)
function moveDiscreteElementToNewCanvas() {
// get the imageData of the main canvas
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
data1 = imageData.data;
// test & return if the main canvas is empty
// Note: do this b/ geom.contour will fatal-error if canvas is empty
var hit = false;
for (var i = 0; i < data1.length; i += 4) {
if (data1[i + 3] > 0) {
hit = true;
break;
}
}
if (!hit) {
return;
}
// get the point-path that outlines a discrete element
var points = geom.contour(defineNonTransparent);
// create a new canvas and append it to page
var newCanvas = document.createElement('canvas');
newCanvas.width = canvas.width;
newCanvas.height = canvas.height;
// newCanvas.style.display = "none";
document.body.appendChild(newCanvas);
canvases.push(newCanvas);
var newCtx = newCanvas.getContext('2d');
// attach the outline points to the new canvas (needed later)
newCanvas.outlinePoints = points;
// draw just that element to the new canvas
defineGeomPath(newCtx, points);
newCtx.save();
newCtx.clip();
newCtx.drawImage(canvas, 0, 0);
newCtx.restore();
// remove the element from the main canvas
defineGeomPath(ctx, points);
ctx.save();
ctx.clip();
ctx.globalCompositeOperation = "destination-out";
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.restore();
return (true);
}
// utility function
// Defines a path on the canvas without stroking or filling that path
function defineGeomPath(context, points) {
context.beginPath();
context.moveTo(points[0][0], points[0][1]);
for (var i = 1; i < points.length; i++) {
context.lineTo(points[i][0], points[i][1]);
}
context.lineTo(points[0][0], points[0][1]);
context.closePath();
}
////////////////////////////
// Edge Detection
///////////////////////////
(function() {
geom = {};
geom.contour = function(grid, start) {
var s = start || d3_geom_contourStart(grid), // starting point
c = [], // contour polygon
x = s[0], // current x position
y = s[1], // current y position
dx = 0, // next x direction
dy = 0, // next y direction
pdx = NaN, // previous x direction
pdy = NaN, // previous y direction
i = 0;
do {
// determine marching squares index
i = 0;
if (grid(x - 1, y - 1)) i += 1;
if (grid(x, y - 1)) i += 2;
if (grid(x - 1, y)) i += 4;
if (grid(x, y)) i += 8;
// determine next direction
if (i === 6) {
dx = pdy === -1 ? -1 : 1;
dy = 0;
} else if (i === 9) {
dx = 0;
dy = pdx === 1 ? -1 : 1;
} else {
dx = d3_geom_contourDx[i];
dy = d3_geom_contourDy[i];
}
// update contour polygon
if (dx != pdx && dy != pdy) {
c.push([x, y]);
pdx = dx;
pdy = dy;
}
x += dx;
y += dy;
} while (s[0] != x || s[1] != y);
return c;
};
// lookup tables for marching directions
var d3_geom_contourDx = [1, 0, 1, 1, -1, 0, -1, 1, 0, 0, 0, 0, -1, 0, -1, NaN],
d3_geom_contourDy = [0, -1, 0, 0, 0, -1, 0, 0, 1, -1, 1, 1, 0, -1, 0, NaN];
function d3_geom_contourStart(grid) {
var x = 0,
y = 0;
// search for a starting point; begin at origin
// and proceed along outward-expanding diagonals
while (true) {
if (grid(x, y)) {
return [x, y];
}
if (x === 0) {
x = y + 1;
y = 0;
} else {
x = x - 1;
y = y + 1;
}
}
}
})();
#canvas {
background: #f0f0f0;
border-radius: 5px;
}
body {
background-color: #333;
color: #fff;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-family: Arial, Helvetica, sans-serif;
min-height: 100vh;
margin: 0;
}
* {
box-sizing: border-box;
}
#source {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=<device-width>, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<link rel='stylesheet' href='https://code.getmdl.io/1.3.0/material.indigo-pink.min.css'>
</head>
<body>
<div class='mdl-grid'>
<div class='mdl-cell mdl-cell--4-col'>
<label id='buttonUpload' for='fileinput' class='mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent'>
<input type='file' id='fileinput' style='display: none'>
Upload
</label>
<div class='mdl-tooltip' for='buttonUpload'>
Upload the image to put inside the marker
</div>
</div>
</div>
<!-- <h4>Original Image</h4> -->
<!-- <img height="200px" width="200px" src="https://cdn.glitch.com/c3106e6c-98cb-40e4-b0c1-85257680d25a%2Fsun.png?v=1564472507237"> -->
<h4>Canvas with sticker effect applied</h4>
<div class="container">
<canvas id="canvas" width="600" height="400"></canvas><br>
</div>
<h4>Each discrete element of the image is processed on a separate canvas<br>Temp-canvases are shown below for illustration purposes only.</h4>
</body>
</html>
I was thinking about how to get something close to what you show in your image:
Maybe if we draw the image offset at different angles we can get something close to that:
var s = 16, x = 25, y = 25;
var ctx = document.getElementById('canvas1').getContext('2d')
var img = new Image;
img.onload = draw1;
img.src = "https://imgur.com/download/oXfw9nD/";
function draw1() {
for (i = 0; i < 360; i++)
ctx.drawImage(img, x + Math.sin(i) * s, y + Math.cos(i) * s);
ctx.filter = 'invert(100)'
ctx.drawImage(img, x, y);
}
<canvas id=canvas1 width=460 height=160></canvas>
You can also add some blur to soften the edges, take a look:
var s = 6, x = 25, y = 25;
var ctx = document.getElementById('canvas1').getContext('2d')
var img = new Image;
img.onload = draw1;
img.src = "https://imgur.com/download/oXfw9nD/";
function draw1() {
ctx.filter = 'blur(5px)'
for (i = 0; i < 360; i++)
ctx.drawImage(img, x + Math.sin(i) * s, y + Math.cos(i) * s);
ctx.globalCompositeOperation = "source-in";
ctx.filter = 'invert(100)'
ctx.globalCompositeOperation = "source-over";
ctx.drawImage(img, x, y);
}
<canvas id=canvas1 width=460 height=160></canvas>
That should get you closer to what you need

Image concatenation script

everyone. I'm trying to write a script that would render images from file inputs on a canvas in a row.
First I cycle through images to calculate the canvas width (because the canvas is wiped on resizing). Then cycle again to render the images.
canvas.width = 0;
let x = 0,
y = 0,
totalWidth = 0;
for (let i = 0; i < document.querySelectorAll(".has-file").length; i++) {
let input = document.querySelectorAll(".has-file")[i];
let image = input.files[0];
let img = new Image();
console.log(img);
img.src = window.URL.createObjectURL(image);
img.addEventListener('load', () => {
console.log(img);
let newWidth = img.width * canvas.height / img.height;
totalWidth += newWidth;
canvas.width = totalWidth;
}, false);
};
for (let i = 0; i < document.querySelectorAll(".has-file").length; i++) {
let input = document.querySelectorAll(".has-file")[i];
let image = input.files[0];
let img = new Image();
img.src = window.URL.createObjectURL(image);
img.addEventListener('load', () => {
let newWidth = img.width * canvas.height / img.height;
ctx.drawImage(img, x, y, newWidth, canvas.height);
x += newWidth;
}, false);
};
}
The app behaves weird, the images are not always rendered, and when they do, not always where they supposed to be.
First problem with the code is that you're loading images twice, and the randomness is due to the fact that image loading can be ambiguous. Check out this jsfiddle. I have used text input instead of files, drawing takes place when it is the last image otherwise resizing the canvas can cause canvas to reset, losing the previous draw.
var canvas = document.getElementById("canvas");
const ctx = canvas.getContext('2d', {
antialias: false,
depth: false
});
canvas.width = 0;
let x = 0,
y = 0,
totalWidth = 0;
let obj = [];
let k = 0;
for (let i = 0; i < document.querySelectorAll(".has-file").length; i++) {
let input = document.querySelectorAll(".has-file")[i];
let image = input.value;
let img = new Image();
img.src = image;//window.URL.createObjectURL(image);
img.addEventListener('load', () => {
console.log(img);
let newWidth = img.width * canvas.height / img.height;
totalWidth += newWidth;
canvas.width = totalWidth;
obj.push({img: img, x: x, y: y, newWidth: newWidth, height: canvas.height});
k++;
x += newWidth;
if (k == document.querySelectorAll(".has-file").length )
draw();
}, false);
};
function draw() {
for (var i = 0; i < obj.length; i++) {
ctx.drawImage(obj[i].img, obj[i].x, obj[i].y, obj[i].newWidth, obj[i].height);
}
}
<input style="display: none;" class="has-file" value="https://i.imgur.com/I86rTVl.jpg" />
<input style="display: none;" class="has-file" value="https://images.unsplash.com/photo-1446292267125-fecb4ecbf1a5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80" />
<canvas id="canvas"></canvas>

Draw SVG on canvas [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have a set of coordinates and for every pair I'd like to place a SVG on the canvas. The problem is in getCircle function. The SVG doesn't work, but if I draw a circle(see commented code) it works.
function getCircle() {
var circle = document.createElement("canvas"),
ctx = circle.getContext("2d"),
r2 = radius + blur;
circle.width = circle.height = r2 * 2;
/*
ctx.shadowOffsetX = ctx.shadowOffsetY = r2 * 2;
ctx.shadowBlur = blur;
ctx.shadowColor = "purple";
ctx.beginPath();
ctx.arc(-r2, -r2, radius, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
*/
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
};
img.src = "https://upload.wikimedia.org/wikipedia/en/0/09/Circle_Logo.svg";
return circle;
}
var radius = 5;
var blur = 1;
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 200;
var circle = getCircle();
ctx.clearRect(0, 0, canvas.width, canvas.height);
var data = [[38,20,2]];
for (var i = 0, len = data.length, p; i < len; i++) {
p = data[i];
ctx.drawImage(circle, p[0] - radius, p[1] - radius);
}
#c {
width: 400px;
height: 200px;
}
<canvas id="c"></canvas>
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 200;
var data = [[0,20,2],[125,20,2],[250,20,2]];
drawImage();
function drawImage() {
var img = new Image();
img.onload = function() {
for (var i = 0, len = data.length, p; i < len; i++) {
p = data[i];
ctx.drawImage(this, p[0] , p[1] , 150, 150);
}
};
img.src = "https://upload.wikimedia.org/wikipedia/en/0/09/Circle_Logo.svg";
}
#c {
width: 400px;
height: 200px;
}
<canvas id="c"></canvas>
in img.onload() draw your image in specified position with widht and height using drawImage().

Shattering image using canvas

I'm trying to shatter image to pieces using canvas , this is my code :
var image = new Image();
image.src = 'koals.jpg';
image.onload = cutImageUp;
var imagePieces = [];
function cutImageUp() {
for(var x = 0; x < 5; x++) {
for(var y = 0; y < 5; y++) {
var canvas = document.createElement('canvas');
canvas.width = 50+"px";
canvas.height = 50+"px";
var context = canvas.getContext('2d');
context.drawImage(image, x *50, y * 50, 50, 50, 0, 0, 50, 50);
imagePieces.push(canvas.toDataURL());
}
}
var anImageElement = document.getElementById('img');
anImageElement.src = imagePieces[0];
}
the problem is that image is returning "blank image" (a.k.a its not loaded);
Console ain't throwing any error.
I'm opening it as local html file , both image and html document are in the same folder so there shouldn't be problem with toDataURL() not returning data due to image being on another domain.
Your problem is with the 50+"px" for canvas width and height, remove the +"px" part and your good.
From w3Specs:
The canvas element has two attributes to control the size of the coordinate space: width and height. These attributes, when specified, must have values that are valid non-negative integers.
var image = new Image();
image.src = 'koals.jpg';
image.onload = cutImageUp;
var imagePieces = [];
function cutImageUp() {
for(var x = 0; x < 5; x++) {
for(var y = 0; y < 5; y++) {
var canvas = document.createElement('canvas');
canvas.width = 50;
canvas.height = 50;
var context = canvas.getContext('2d');
context.drawImage(image, x *50, y * 50, 50, 50, 0, 0, 50, 50);
imagePieces.push(canvas.toDataURL());
}
}
var anImageElement = document.getElementById('img');
anImageElement.src = imagePieces[0];
}
jsfiddle

putImageData will not draw to the canvas

After splitting up the tileset http://mystikrpg.com/images/all_tiles.png
It still will not draw onto the <canvas> I know it gets put into the tileData[] because it outputs ImageData in the console.log(tileData[1]).
$(document).ready(function () {
var tileWidth, tileHeight
ImageWidth = 736;
ImageHeight = 672;
tileWidth = 32;
tileHeight = 32;
console.log("Client setup...");
canvas = document.getElementById("canvas");
canvas.width = 512;
canvas.height = 352;
context = canvas.getContext("2d");
canvas.tabIndex = 0;
canvas.focus();
console.log("Client focused.");
var imageObj = new Image();
imageObj.src = "./images/all_tiles.png";
imageObj.onload = function() {
context.drawImage(imageObj, ImageWidth, ImageHeight);
var allLoaded = 0;
var tilesX = ImageWidth / tileWidth;
var tilesY = ImageHeight / tileHeight;
var totalTiles = tilesX * tilesY;
for(var i=0; i<tilesY; i++)
{
for(var j=0; j<tilesX; j++)
{
// Store the image data of each tile in the array.
tileData.push(context.getImageData(j*tileWidth, i*tileHeight, tileWidth, tileHeight));
allLoaded++;
}
}
if (allLoaded == totalTiles) {
console.log("All done: " + allLoaded); // 483
console.log(tileData[1]); // > ImageData
startGame();
}
};
});
also
var startGame = function () {
console.log("Trying to paint test tile onto convas...");
try {
context.putImageData(tileData[0], 0, 0);
} catch(e) {
console.log(e);
}
}
When you draw the image to the canvas initially, why are you:
context.drawImage(imageObj, ImageWidth, ImageHeight);
Looks like you may have the parameters confused and are trying to fill the area with ImageWidth, ImageHeight... instead, draw it to 0,0
context.drawImage(imageObj, 0, 0);
Here's your code adjusted a little bit:
var tileData = [];
var tileWidth, tileHeight
var ImageWidth = 736;
var ImageHeight = 672;
var tileWidth = 32;
var tileHeight = 32;
var tilesX;
var tilesY
var totalTiles;
canvas = document.getElementById("canvas");
canvas.width = ImageWidth;
canvas.height = ImageHeight;
context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.src = "all_tiles.png";
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
// draw the image to canvas so you can get the pixels context.drawImage(imageObj, 0, 0);
tilesX = ImageWidth / tileWidth;
tilesY = ImageHeight / tileHeight;
totalTiles = tilesX * tilesY;
for(var i=0; i<tilesY; i++) {
for(var j=0; j<tilesX; j++) {
// Store the image data of each tile in the array.
tileData.push(context.getImageData(j*tileWidth, i*tileHeight, tileWidth, tileHeight));
}
}
// test it...
// blank the canvas and draw tiles back in random positions
context.fillStyle = "rgba(255,255,255,1)";
context.fillRect(0,0,canvas.width, canvas.height);
for ( i = 0; i < 20; i++ ) {
context.putImageData(tileData[ i ], Math.random() * canvas.width, Math.random() * canvas.height );
}
};
There's no need to test 'all loaded' since it's just one image that you're splitting apart.

Categories

Resources