I new in the game dev and cocos.
So, I have following grid:
1|2|3|4
5|6|7|8
9|1|2|3
User can scroll row or columns around.
For example, if user scroll first row by one position we got following grig:
4|1|2|3
5|6|7|8
9|1|2|3
How I can do in with cocos2d js? Which components use for that?
Now I try create grid:
for (var i = 0; i < 16; i++) {
var tile = new NumberTile(i);
tile.pictureValue = gameArray[i];
this.addChild(tile, 0);
tile.setPosition(49 + i % 4 * 74, 400 - Math.floor(i / 4) * 74);
}
And add to game Layer.
NumberTile - its sprite with number. But I don't know how to scroll rows and columns around.
use a vertical scrollview as container, add add horizontal scrollviews into it.
var HelloWorldLayer = cc.Layer.extend({
sprite: null,
ctor: function() {
// 1. super init first
this._super();
var count = 10;
var size = cc.winSize;
var w = size.width;
var h = size.height / 4;
var c_container = new cc.Node();
c_container.setContentSize(cc.size(w, h * count));
var container = new cc.ScrollView(size, c_container);
container.setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL);
for (var i = 0; i < count; i++) {
var child = new cc.Node();
child.setContentSize(cc.size(w, h));
this.createSubScrollView(child);
child.setPosition(cc.p(0, h * i));
container.addChild(child);
}
var f1 = container.getAnchorPoint();
container.setPosition(cc.p(0, 0));
this.addChild(container);
return true;
},
createSubScrollView: function(container) {
var size = container.getContentSize();
var count = 10;
var w = size.width / 4;;
var h = size.height;
var c_container = new cc.Node();
c_container.setContentSize(cc.size(w * count, h));
var scroll = new cc.ScrollView(size, c_container);
scroll.setDirection(cc.SCROLLVIEW_DIRECTION_HORIZONTAL);
for (var i = 0; i < count; i++) {
var child = new cc.Node();
child.setContentSize(cc.size(w, h));
var color = i % 2 == 0 ? cc.color.RED : cc.color.GREEN;
var c = new cc.LayerColor(color, w, h);
child.addChild(c);
var label = new cc.LabelTTF("" + i, "Arial", 20);
label.setPosition(cc.p(w * 0.5, h * 0.5));
child.addChild(label);
child.setPosition(cc.p(w * i, 0));
scroll.addChild(child);
}
container.addChild(scroll);
},
});
add here is what it acts
Related
I am now working with a Web Application, which needs to draw some cards on a fixed rectangle canvas. Below is the criteria:
The canvas size is fixed with width "w" and height "h" when the Web Application starts.
There are "n" no. of cards which won't be changed after started.
All cards must in the same size, which has a fixed ratio with width "cw" and height "ch", the cards are able to re-size within the canvas.
I would like to calculate the maximum width and height of each card in such cases. Can anybody help?
Your question is lacking a lot of information. please read the comments in the code. I hope my answer may help you.
// initiate the canvas
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let cw = canvas.width = 300,
cx = cw / 2;
let ch = canvas.height = 300,
cy = ch / 2;
// number of cards
let n = 12;
// the horizontal and vertical ratio
let ratio = {x:.2,y:.3}
// the width and the height of a card
let w = cw*ratio.x;
let h = ch*ratio.y;
// a counter
let i = 0;
//a double for loop to draw the cards
for(let y = 0; y<ch; y+=h){
for(let x = 0; x<cw; x+=w){
if(i < n)
{drawCard(x,y);
i++}
}
}
function drawCard(x,y){
ctx.beginPath();
ctx.strokeRect(x,y,w,h);
}
canvas {
border:1px solid #d9d9d9;
}
<canvas id="canvas"></canvas>
Finally, I found the solution myself.
This performance may not is the optimal one, but the solution gives me the new card width, new card height, cards per rows and cards per column. So that the cards can almost cover the canvas.
function crwh(col, row, n, cw, ch, w, h, exactN) {
// Methods
this.fn_init = function(col, row) {
this.col = col;
this.row = row;
if (this.col > 0 && this.row > 0) {
// Calculate new card width & card height base on col
this.cw_new = (this.w / this.col);
this.ch_new = (this.cw_new / this.cw * this.ch);
if (this.fn_valid() == false) {
// Calculate new card height & card width base on row
this.ch_new = (this.h / this.row);
this.cw_new = (this.ch_new / this.ch * cw);
}
}
}
this.fn_area = function() {
// Get the size the rectangle
return this.cw_new * this.ch_new;
}
this.fn_valid = function() {
var valid = true;
// True if col * row must equal to no. of cards, False allow col * row greater than no. of cards
valid = valid && ((this.exactN == true && (this.col * this.row) == this.n) || (this.exactN == false && (this.col * this.row) >= this.n));
// col * card width (new) must be shorter than canvas width
valid = valid && ((this.col * this.cw_new) <= this.w);
// row * card height (new) must be shorter than canvas height
valid = valid && ((this.row * this.ch_new) <= this.h);
return valid;
}
// Properties
this.n = n;
this.cw = cw;
this.ch = ch;
this.w = w;
this.h = h;
this.exactN = exactN;
this.col = 0;
this.row = 0;
this.cw_new = 0;
this.ch_new = 0;
this.fn_init(col, row);
}
function fn_getCardDimensions(n, cw, ch, w, h, exactN) {
var crwh_max = new crwh(0, 0);
// Loop thru 1 to n for col & row to see which combination allow a maximum card size
for (var col = 1; col <= n; col++) {
for (var row = 1; row <= n; row++) {
if ((col * row) >= n) {
var crwh_cur = new crwh(col, row, n, cw, ch, w, h, exactN);
if (crwh_cur.fn_valid()) {
if (crwh_cur.fn_area() > crwh_max.fn_area()) {
crwh_max = crwh_cur;
}
}
}
}
}
return [crwh_max.col, crwh_max.row, crwh_max.cw_new, crwh_max.ch_new];
}
var n = 80; // No. of Cards
var cw = 344; // Card Width (orig)
var ch = 512; // Card Height (orig)
var w = 0; // Canvas Width
var h = 0; // Canvas Height
var exactN = true; // True if col * row must equal to no. of cards
function fn_drawCards() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
[col, row, cw_new, ch_new] = fn_getCardDimensions(n, cw, ch, w, h, exactN);
for (var i = 0; i < col; i++) {
for (var j = 0; j < row; j++) {
ctx.beginPath();
ctx.strokeRect(i * cw_new, j * ch_new, cw_new, ch_new);
}
}
}
fn_drawCards();
canvas {
border:1px solid #00FF00;
}
<canvas id="canvas"></canvas>
How to Save positions for 3 objects in Array to make random position between each other by AS3?
import flash.geom.Point;
var arry:Point = new Point();
arry[0] = arry[78,200];
arry[1] = arry[217,200];
arry[2] = arry[356,200];
//object called b1
b1.x = arry[0][0];
b1.y = arry[0][1];
//object called b2
b2.x = arry[1][0];
b2.y = arry[1][1];
//object called b3
b3.x = arry[2][0];
b3.y = arry[2][1];
//make objects swap positions between each other
var rand:Number = (Math.random()*arry.length);
//output to see random position [[78,200],[217,200],[356,200]]
trace(arry);
to get random with tween like this... https://www.youtube.com/watch?v=8m_m64plQ6E
At compile time you should get this Error I suppose : "ReferenceError: Error #1069"
Here is a way to store the positions (like in the link you provided from youtube) :
import flash.geom.Point;
var squareWidth:uint = 40;
var squareHeight:uint = 40;
var marginX:uint = 100;
var marginY:uint = 75;
var spacer:uint = 10;
var positions:Vector.<Point > = new Vector.<Point > (9);
function setPositions(v:Vector.<Point>):void {
var count:uint = 0;
var posx:uint;
var posy:uint;
for (var i = 0; i < 3; i ++)
{
for (var j = 0; j < 3; j ++)
{
posx = (j * squareWidth) + (spacer * j) + marginX;
posy = (i * squareHeight) + (spacer * i) + marginY;
v[count] = new Point(posx,posy);
count++;
}
}
}
setPositions(positions);
trace(positions);
// output :
// (x=100, y=75),(x=150, y=75),(x=200, y=75),(x=100, y=125),(x=150, y=125),(x=200, y=125),(x=100, y=175),(x=150, y=175),(x=200, y=175)
So here you have nine Points to place the clips like in the video.
You just have to add a function to swap the nine boxes stored in another Vector.
In your case.
For 3 positions do the following if I understand your question.
import flash.geom.Point;
var positions:Vector.<Point> = new Vector.<Point>(3);
var p1:Point = new Point(78,200);
var p2:Point = new Point(217,200);
var p3:Point = new Point(356,200);
positions[0] = p1;
positions[1] = p2;
positions[2] = p3;
trace(positions);
// output : (x=78, y=200),(x=217, y=200),(x=356, y=200)
So, you're still unclear!
Your issue is to find a random position?
This may help you if this is the problem you're facing :
import flash.geom.Point;
var positions:Vector.<Point > = new Vector.<Point > (3);
var numbers:Vector.<uint> = new Vector.<uint>();
var numbersAllowed:uint = 3;
var rndNmbrs:Vector.<uint> = new Vector.<uint>(3);;
var p1:Point = new Point(78,200);
var p2:Point = new Point(217,200);
var p3:Point = new Point(356,200);
positions[0] = p1;
positions[1] = p2;
positions[2] = p3;
trace(positions);
function populateRndNmbrs(n:uint):void {
for (var i:uint = 0; i < n; i++)
{
numbers[i] = i;
}
}
populateRndNmbrs(numbersAllowed);
function populateRandomNumbers(n:uint):void
{
var rnd:uint;
for (var i:uint = 0; i < n; i++)
{
rnd = numbers[Math.floor(Math.random() * numbers.length)];
for (var j:uint = 0; j < numbers.length; j++)
{
if (rnd == numbers[j])
{
numbers.splice(j,1);
}
}
rndNmbrs[i] = rnd;
}
}
populateRandomNumbers(numbersAllowed);
trace("rndNmbrs = " + rndNmbrs);
for (var i:uint = 0; i < numbersAllowed; i++)
{
trace("b"+ (i+1) + ".x = " + positions[rndNmbrs[i]].x);
trace("b"+ (i+1) + ".y = " + positions[rndNmbrs[i]].y);
// In place of trace, you should place the boxes at those random positions.;
}
//output:
//(x=78, y=200),(x=217, y=200),(x=356, y=200)
//rndNmbrs = 2,0,1
//b1.x = 356
//b1.y = 200
//b2.x = 78
//b2.y = 200
//b3.x = 217
//b3.y = 200
Is that what you want? Or do you want to know how to create a motion effect?
I'm not sure about what you really need...
This will help you to place all the boxes in a random position.
You may do this like here bellow, and add a function to check if the random positions are not the same.
With only 3 MovieClips, you will often have the same random positions as long they're stored in the "positions Vector"
var squares:Vector.<MovieClip> = new Vector.<MovieClip>(3);
function populateMCs(target:DisplayObjectContainer,n:uint):void{
for (var i:uint = 0; i < n; i++){
squares[i] = target["b"+(i+1)];
}
}
function swapMCs():void{
for (var i:uint=0; i<squares.length; i++){
squares[i].x = positions[rndNmbrs[i]].x;
squares[i].y = positions[rndNmbrs[i]].y;
}
}
populateMCs(this,numbersAllowed);
swapMCs();
I give you a last example to get a motion effect in AS3.
I'm not a translator AS2 -> AS3 and a video is not the best way to show your code :(
This will make your boxes move smoothly, but not the way you want.
Now, you have to learn AS3 and try to make the job by yourself.
Then, if you have another issue, just ask clearly what you want.
var friction:Number = 0.15;
setDestination(squares[0],squares[0].x,350,friction);
setDestination(squares[1],squares[1].x,350,friction);
setDestination(squares[2],squares[2].x,350,friction);
squares[0].addEventListener(Event.ENTER_FRAME,moveClip);
squares[1].addEventListener(Event.ENTER_FRAME,moveClip);
squares[2].addEventListener(Event.ENTER_FRAME,moveClip);
function setDestination(mc:MovieClip,x:uint,y:uint,friction:Number):void{
mc.destinx = x;
mc.destiny = y;
mc.f = friction;
}
function moveClip(e:Event):void{
var mc:MovieClip = e.target as MovieClip;
trace(mc.name)
mc.speedx = (mc.destinx - mc.x);
mc.speedy = (mc.destiny - mc.y);
mc.x += mc.speedx*mc.f;
mc.y += mc.speedy*mc.f;
if((Math.floor(mc.speedx)<1) && (Math.floor(mc.speedy)<1)){
mc.removeEventListener(Event.ENTER_FRAME,moveClip);
trace("STOP MOVE FOR " + mc.name);
}
}
im making a code where I have an input field and a button on my screen. In the code below btnLeggTil (its norwegian) adds the number you wrote in the input field. It determines the height of the bars. My code is supposed to let the user add bars of whatever the height he/she prefers. As you can see I have put alot of my code inside a loop. The problem with the code is that the bars it makes, overlap eachother. I need to have a space between each bar, but don't know how. Thanks in advance! You can test out the code yourself and see (just remember to make a button and input field with names btnLeggTil and txtInn.
("høyde" means height) ("bredde" means width) ("verdier" means values) sorry its all norwegian
var verdier:Array = new Array();
btnLeggTil.addEventListener(MouseEvent.CLICK, leggtil);
function leggtil (evt:MouseEvent)
{
verdier.push(txtInn.text);
var totHøyde:int = 200; //total height on diagram
var totBredde:int = 450; //total width on diagram
var antall:int = verdier.length;
var xv:int = 50;
var yb:int = 350;
var bredde:int = (totBredde/antall) * 0.8;
var mellom:int = (totBredde/antall) * 0.2;
var maksHøyde:int = maksVerdi(verdier);
function maksVerdi(arr:Array):Number //finds the biggest value in the array
{
//copies to not destroy the order in the original
var arrKopi:Array = arr.slice();
arrKopi.sort(Array.NUMERIC|Array.DESCENDING);
return arrKopi[0];
}
for(var i:int = 0; i < verdier.length; i++)
{
graphics.lineStyle(2, 0x000000);
graphics.beginFill(0x00ff00);
graphics.drawRect(xv + (bredde+mellom)*i, yb, bredde, -verdier[i] * (totHøyde/maksHøyde));
graphics.endFill();
var txtTall = new TextField();
txtTall.x = xv + (bredde+mellom)*i + 5;
txtTall.y = yb - verdier[i] - 10;
txtTall.type = "dynamic";
txtTall.text = verdier[i];
addChild(txtTall);
}
}
You need to modify your for loop a bit,
graphics.clear();
graphics.lineStyle(2, 0x000000);
graphics.beginFill(0x00ff00);
for(var i:int = 0; i < verdier.length; i++)
{
graphics.drawRect(xv + (bredde+mellom)*i, yb, bredde, -verdier[i] * (totHøyde/maksHøyde));
var txtTall = new TextField();
txtTall.x = xv + (bredde+mellom)*i + 5;
txtTall.y = yb - verdier[i] - 10;
txtTall.type = "dynamic";
txtTall.text = verdier[i];
addChild(txtTall);
}
graphics.endFill();
I am making a tool which obscures an image with squares. What I want to happen is to have a bouncing ball which hits the squares and makes them disappear. However, the removeChild command isn't working right. I set it up to populate the image with empty movie clips and colorize them. However, when I click the square, I am running into problems with the parent/child. I keep running into this error. "The supplied DisplayObject must be a child of the caller." I cannot think of a good way to assign the eventListeners to each individual squares. I'm sure it is obvious. Here is my code. Thank you in advance
EDIT:If I get it to work, it deletes all instances of the square, not just the one I clicked.
Here is my code
var mc:MovieClip = bgIMG;
var bd:BitmapData = new BitmapData(mc.width,mc.height);
bd.draw(mc);
var _img:Bitmap = new Bitmap(bd);
var _imgNodes:Array = [];
var _tiledImg:MovieClip = container_tiled_img;
var pad:int = 0;
var rows:int = 10;
var cols:int = 10;
var zero:Point = new Point();
createImgNodeGrid(rows, cols, pad);
pixelateNodes(_imgNodes);
function removeMC(e:MouseEvent)
{//removes the movie clip
trace(e.currentTarget.x);
stage.removeChild(e.currentTarget.parent.parent);
}
function pixelateNodes(nodes:Array = null):void
{
for each (var node:Bitmap in nodes)
{
node.bitmapData.fillRect(node.bitmapData.rect, avgColor(node.bitmapData));
}
}
function avgColor(src:BitmapData):uint
{
var A:Number = 0;
var R:Number = 0;
var G:Number = 0;
var B:Number = 0;
var idx:Number = 0;
var px:Number;
for (var x:int = 0; x < src.width; x++)
{
for (var y:int = 0; y < src.height; y++)
{
px = src.getPixel32(x,y);
A += px >> 24 & 0xFF;
R += px >> 16 & 0xFF;
G += px >> 8 & 0xFF;
B += px & 0xFF;
idx++;
}
}
A /= idx;
R /= idx;
G /= idx;
B /= idx;
return A << 24 | R << 16 | G << 8 | B;
}
function createImgNodeGrid(rows:int = 1, cols:int = 1, pad:Number = 0):void
{
var w:Number = _img.width / rows;
var h:Number = _img.height / cols;
var numNodes:int = rows * cols;
_imgNodes = [];
var nodeCount:int = 0;
for (var i:int = 0; i < rows; i++)
{
for (var j:int = 0; j < cols; j++)
{
// get area of current image node
var sourceRect:Rectangle = new Rectangle(i * w, j * h, w, h);
// copy bitmap data of current image node
var tempBd:BitmapData = new BitmapData(w,h,true);
tempBd.copyPixels(_img.bitmapData, sourceRect, zero);
// place image node bitmap data into sprite
var imgNode:Bitmap = new Bitmap(tempBd);
imgNode.x = i * (w + pad);
imgNode.y = j * (h + pad);
// store each image node
//_imgNodes.push(imgNode);
_imgNodes[nodeCount++] = imgNode;
// add each image node to the stage
_tiledImg.addChild(imgNode);
_tiledImg.addEventListener(MouseEvent.CLICK,removeMC);
}
}
}
The problem you have is your are adding the event to the parent of the node(_tiledImg).
function createImgNodeGrid(rows:int = 1, cols:int = 1, pad:Number = 0):void
{
var w:Number = _img.width / rows;
var h:Number = _img.height / cols;
var numNodes:int = rows * cols;
_imgNodes = [];
var nodeCount:int = 0;
for (var i:int = 0; i < rows; i++)
{
for (var j:int = 0; j < cols; j++)
{
// get area of current image node
var sourceRect:Rectangle = new Rectangle(i * w, j * h, w, h);
// copy bitmap data of current image node
var tempBd:BitmapData = new BitmapData(w,h,true);
tempBd.copyPixels(_img.bitmapData, sourceRect, zero);
// place image node bitmap data into sprite
var imgNode:Bitmap = new Bitmap(tempBd);
imgNode.x = i * (w + pad);
imgNode.y = j * (h + pad);
// store each image node
//_imgNodes.push(imgNode);
_imgNodes[nodeCount++] = imgNode;
// you need a container since you can not attach event listeners to a BitMap
var sprite:Sprite = new Sprite()
sprite.mouseChildren = false;
sprite.addEventListener(MouseEvent.CLICK,removeMC);
sprite.addChild(imgNode);
// add each image node to the stage
_tiledImg.addChild(sprite);
// _tiledImg.addEventListener(MouseEvent.CLICK,removeMC);
}
}
}
function removeMC(e:MouseEvent)
{
var target:Sprite = event.currentTarget as Sprite;
target.parent.removeChild(target)
}
If I am following correctly, you are trying to remove an imgNode on MouseClick. If that is the case, you should change removeMC function to this:
function removeMC(e:MouseEvent)
{
//removes the movie clip
trace(e.target);
_tiledImg.removeChild(event.currentTarget);
}
Also, you shouldn't add the listener within the for loop, but instead add it outside of the for loops (since you are just adding the listener to _tiledImg and that doesn't change in the for loops).
A easy way to always remove a child from the right parent is to do as following
function removeMC(e:MouseEvent)
{
//removes the movie clip
var target:Sprite = event.currentTarget as Sprite;
target.parent.removeChild(target)
}
UPDATE: Once I got this demo working... holy smokes, it's SLOW, like 12-16 seconds for only a level 2 render (when image is around 1000x2000 pixels). This is not even worth bothering with.
I found this really awesome and hopeful looking code in the top answer here: Resizing an image in an HTML5 canvas
//returns a function that calculates lanczos weight
function lanczosCreate(lobes){
return function(x){
if (x > lobes)
return 0;
x *= Math.PI;
if (Math.abs(x) < 1e-16)
return 1
var xx = x / lobes;
return Math.sin(x) * Math.sin(xx) / x / xx;
}
}
//elem: canvas element, img: image element, sx: scaled width, lobes: kernel radius
function thumbnailer(elem, img, sx, lobes){
this.canvas = elem;
elem.width = img.width;
elem.height = img.height;
elem.style.display = "none";
this.ctx = elem.getContext("2d");
this.ctx.drawImage(img, 0, 0);
this.img = img;
this.src = this.ctx.getImageData(0, 0, img.width, img.height);
this.dest = {
width: sx,
height: Math.round(img.height * sx / img.width),
};
this.dest.data = new Array(this.dest.width * this.dest.height * 3);
this.lanczos = lanczosCreate(lobes);
this.ratio = img.width / sx;
this.rcp_ratio = 2 / this.ratio;
this.range2 = Math.ceil(this.ratio * lobes / 2);
this.cacheLanc = {};
this.center = {};
this.icenter = {};
setTimeout(this.process1, 0, this, 0);
}
thumbnailer.prototype.process1 = function(self, u){
self.center.x = (u + 0.5) * self.ratio;
self.icenter.x = Math.floor(self.center.x);
for (var v = 0; v < self.dest.height; v++) {
self.center.y = (v + 0.5) * self.ratio;
self.icenter.y = Math.floor(self.center.y);
var a, r, g, b;
a = r = g = b = 0;
for (var i = self.icenter.x - self.range2; i <= self.icenter.x + self.range2; i++) {
if (i < 0 || i >= self.src.width)
continue;
var f_x = Math.floor(1000 * Math.abs(i - self.center.x));
if (!self.cacheLanc[f_x])
self.cacheLanc[f_x] = {};
for (var j = self.icenter.y - self.range2; j <= self.icenter.y + self.range2; j++) {
if (j < 0 || j >= self.src.height)
continue;
var f_y = Math.floor(1000 * Math.abs(j - self.center.y));
if (self.cacheLanc[f_x][f_y] == undefined)
self.cacheLanc[f_x][f_y] = self.lanczos(Math.sqrt(Math.pow(f_x * self.rcp_ratio, 2) + Math.pow(f_y * self.rcp_ratio, 2)) / 1000);
weight = self.cacheLanc[f_x][f_y];
if (weight > 0) {
var idx = (j * self.src.width + i) * 4;
a += weight;
r += weight * self.src.data[idx];
g += weight * self.src.data[idx + 1];
b += weight * self.src.data[idx + 2];
}
}
}
var idx = (v * self.dest.width + u) * 3;
self.dest.data[idx] = r / a;
self.dest.data[idx + 1] = g / a;
self.dest.data[idx + 2] = b / a;
}
if (++u < self.dest.width)
setTimeout(self.process1, 0, self, u);
else
setTimeout(self.process2, 0, self);
};
thumbnailer.prototype.process2 = function(self){
self.canvas.width = self.dest.width;
self.canvas.height = self.dest.height;
self.ctx.drawImage(self.img, 0, 0);
self.src = self.ctx.getImageData(0, 0, self.dest.width, self.dest.height);
var idx, idx2;
for (var i = 0; i < self.dest.width; i++) {
for (var j = 0; j < self.dest.height; j++) {
idx = (j * self.dest.width + i) * 3;
idx2 = (j * self.dest.width + i) * 4;
self.src.data[idx2] = self.dest.data[idx];
self.src.data[idx2 + 1] = self.dest.data[idx + 1];
self.src.data[idx2 + 2] = self.dest.data[idx + 2];
}
}
self.ctx.putImageData(self.src, 0, 0);
self.canvas.style.display = "block";
}
...
img.onload = function() {
var canvas = document.createElement("canvas");
new thumbnailer(canvas, img, 188, 3); //this produces lanczos3
//but feel free to raise it up to 8. Your client will appreciate
//that the program makes full use of his machine.
document.body.appendChild(canvas);
}
However, this implementation loads an image and renders it, end of story.
I have been trying to re-implement this code so that it does the filtering every time an existing canvas is scaled (think, zooming in and out of an image or document) without having to load a new image or create a new canvas.
How can I adapt it to work this way? Or is that even possible?
What you want to do is something like a singleton to reuse your canvas object. This will let you save the cost of create a new canvas object each time and you will reuse the same object
function getCanvas(){
var canvas;
if (typeof canvas === "undefined"){ canvas = document.createElement("canvas");}
return canvas;
}
img.onload = function() {
var canvas = getCanvas("canvas");
.... THE REST OF YOUR CODE .......
}
.
However this is not what slows your code, image scaling Algorithms are really heavy algorithms with intensive cpu use "usually make use of gpu acceleration at a really low level", and use advanced techniques like multiple bufferr and so others. here is a interesting tutorial in java.net on how image scaling works, it is in java but you can interpolate to any language.
Javascript is not ready for this techniques, so I recommend you to use the transformations available in the canvas api, as in the tutorial you read the efficient way is using the canvas2Dcontext.
var ctx = canvas.getContext("2d");
ctx.scale(2,2);