how to make a function to print a width of an image - javascript

I want to make a function, that prints a width and height of an image
var a = 3;
var s = 2 * a;
var d = a * s;
print(d);
function cube(y) {
return y * y * y;
}
var g = cube(3);
print("g: " + g);
print("h: " + cube(99));
var img = new SimpleImage("drewRobert.png");
var imgN = img.setSize(75, 75);
print(img);
var t = new SimpleImage(25, 25);
print(t);
var img9 = new SimpleImage("drewRobert.png");
var img9N = img9.getPixel(77, 90);
print(img9N);
var img8N = img9.getGreen(0, 0);
print(img8N);
function alo(s, f, j) {
return s + f + j;
}
var sd = alo(9, 3, 1);
print(sd);
img5 = new SimpleImage("palm-and-beach.png");
//that'S one here
function printW(w) {
img5 = new SimpleImage("palm-and-beach.png");
return w = print(img5.getWidth());
}
print(printW(w));
<script src="https://www.dukelearntoprogram.com/course1/common/js/cs101/SimpleImage.js"></script>

Related

JS: Function is not defined

I've been trying to make somekind of a starry sky. Here's the code.
When I'm trying to load the page, the console says that createHtmlElementFromStaris not defined. I can't find out why.
Thanks for your answers in advance!
var Star = function (x, y, look, color) {
var _x = x;
var _y = y;
var _look = look;
var _color = color;
this.createHtmlElementFromStar = function () {
var st = document.createElement("span");
st.style.position = "absolute";
st.style.left = x + "px";
st.style.top = (y - 10) + "px";
return st;
};
};
var Stars = function () {
var _stars = new Array();
this.createStars = function (look, count) {
var x = Math.random() * (400 - x) + x;
var y = Math.random() * (400 - y) + y;
var look = "";
var color = "#"+((1<<24)*Math.random()|0).toString(16);
_stars.push(new Star(x, y, look, color));
};
this.showStars = function () {
for (var i = 0; i < _stars.length; i++) {
document.body.appendChild(createHtmlElementFromStar(_stars[i]));
};
};};
var stars = new Stars();
stars.createStars(1, 50, "*", 150);
stars.showStars();

Draw text pixel by pixel on canvas

I have a canvas where I use "fillText" with a string, saying for example "stackoverflow". Then I read the imagedata of the canvas in order to pick out each pixel of that text.
I want to pick the following from the pixel: x position, y position and its color. Then I would like to loop over that array with those pixels so I can draw back the text pixel by pixel so I have full control of each pixel, and can for example animate them.
However, I dont get it as smooth as I want. Look at my attach image, and you see the difference between the top text and then the text I've plotted out using fillRect for each pixel. Any help on how to make the new text look like the "fillText" text does?
Thanks
UPDATE: Added my code
var _particles = [];
var _canvas, _ctx, _width, _height;
(function(){
init();
})();
function init(){
setupParticles(getTextCanvasData());
}
function getTextCanvasData(){
// var w = 300, h = 150, ratio = 2;
_canvas = document.getElementById("textCanvas");
// _canvas.width = w * ratio;
// _canvas.height = h * ratio;
// _canvas.style.width = w + "px";
// _canvas.style.height = h + "px";
_ctx = _canvas.getContext("2d");
_ctx.fillStyle = "rgb(0, 154, 253)";
// _ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
var str = "stackoverflow";
_ctx.font = "32px EB Garamond";
_ctx.fillText(str,0,23);
_width = _canvas.width;
_height = _canvas.height;
var data32 = new Uint32Array(_ctx.getImageData(0, 0, _width, _height).data.buffer);
var positions = [];
for(i = 0; i < data32.length; i++) {
if (data32[i] & 0xffff0000) {
positions.push({
x: (i % _width),
y: ((i / _width)|0),
});
}
}
return positions;
}
function setupParticles(positions){
var i = positions.length;
var particles = [];
while(i--){
var p = new Particle();
p.init(positions[i]);
_particles.push(p);
drawParticle(p);
}
}
function drawParticle(particle){
var x = particle.x;
var y = particle.y;
_ctx.beginPath();
_ctx.fillRect(x, y, 1, 1);
_ctx.fillStyle = 'green';
}
function Particle(){
this.init = function(pos){
this.x = pos.x;
this.y = pos.y + 30;
this.x0 = this.x;
this.y0 = this.y;
this.xDelta = 0;
this.yDelta = 0;
}
}
Here is an update to your code that reuses the alpha component of each pixel. There will still be some detail lost because we do not keep the antialiasing of the pixels (which in effect alters the actual color printed), but for this example the alpha is enough.
var _particles = [];
var _canvas, _ctx, _width, _height;
(function(){
init();
})();
function init(){
setupParticles(getTextCanvasData());
}
function getTextCanvasData(){
// var w = 300, h = 150, ratio = 2;
_canvas = document.getElementById("textCanvas");
// _canvas.width = w * ratio;
// _canvas.height = h * ratio;
// _canvas.style.width = w + "px";
// _canvas.style.height = h + "px";
_ctx = _canvas.getContext("2d");
_ctx.imageSmoothingEnabled= false;
_ctx.fillStyle = "rgb(0, 154, 253)";
// _ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
var str = "stackoverflow";
_ctx.font = "32px EB Garamond";
_ctx.fillText(str,0,23);
_width = _canvas.width;
_height = _canvas.height;
var pixels = _ctx.getImageData(0, 0, _width, _height).data;
var data32 = new Uint32Array(pixels.buffer);
var positions = [];
for(i = 0; i < data32.length; i++) {
if (data32[i] & 0xffff0000) {
positions.push({
x: (i % _width),
y: ((i / _width)|0),
a: pixels[i*4 + 3] / 255
});
}
}
return positions;
}
function setupParticles(positions){
var i = positions.length;
var particles = [];
while(i--){
var p = new Particle();
p.init(positions[i]);
_particles.push(p);
drawParticle(p);
}
}
function drawParticle(particle){
var x = particle.x;
var y = particle.y;
_ctx.beginPath();
_ctx.fillStyle = `rgba(0,128,0,${particle.alpha})`;
_ctx.fillRect(x, y, 1, 1);
}
function Particle(){
this.init = function(pos){
this.x = pos.x;
this.y = pos.y + 30;
this.x0 = this.x;
this.y0 = this.y;
this.xDelta = 0;
this.yDelta = 0;
this.alpha = pos.a;
}
}
<canvas id="textCanvas"></canvas>

Javascript Canvas DrawImage dissapears previus state

my problem is when i use function drawImage() previus image on canvas has disappered. How i can rember previus state on my canvas?
I use react.
I try use save() and restore() but that not help me.
My code is:
updateCanvas(size, map, src) {
var PSI = 256;
var BSI = 16;
var IZ = PSI;
var crop_canvas = document.getElementById('myCanvas').getContext('2d');//this.refs.canvas.getContext('2d');
console.log(crop_canvas);
if(this.state.widthCanvas < size[0]) {
this.setState({
widthCanvas: size[0]
});
}
var oiw = size[0];
var iw = (oiw + PSI - 1) & ~(PSI - 1);
var dmap = map;
var pos_x = 0;
var pos_y = this.state.heightCanvas;
var myImage = [];
var loadnumber = this.state.loadNumber;
myImage[loadnumber] = new Image();
this.setState({
heightCanvas: this.state.heightCanvas+size[1]
});
myImage[loadnumber].src = src;
myImage[loadnumber].onload = function(e){
$.each(dmap, function(index, value){
var cord = [];
var y = (value / (iw / PSI)) | 0;
var x = (value % (iw / PSI)) | 0;
cord[0] = (x * PSI);
cord[1] = (y * PSI);
var cut_x = ((cord[0] * (2 * BSI + PSI) / PSI + BSI) * IZ / (PSI)) | 0;
var cut_y = ((cord[1] * (2 * BSI + PSI) / PSI + BSI) * IZ / (PSI)) | 0;
crop_canvas.drawImage(myImage[loadnumber] , cut_x, cut_y, PSI, PSI, pos_x, pos_y, PSI, PSI);
pos_x=pos_x+PSI;
if(pos_x > oiw){
pos_y=pos_y+PSI;
pos_x = 0;
}
});
var that = this;
setTimeout(function(){
that.LoaderImage(parseInt(that.state.loadNumber)+1);
},1000);
}.bind(this);
}

How to set onclick event in moving object in canvas?

How to set on click event in moving object in canvas? Also how to move the object bottom to top in canvas.I am newly in javascript i am going to develop the sample like when the page open, objects like square and circle randomly come from bottom of the page and move to top automatically.
You need to establish an array that will have your moving objects in it. When the onclick handler fires, check to see if the coordinates of the click are inside any of the objects in the array.
On each animation frame, move your objects up by subtracting some of the y coordinate from each object.
//width and height of canvas...
var rW = 400;
var rH = 500;
var coinImage = getCoinImage();
var coinsOnScreen = [];
var risingSpeed = 100; //pixels per second...
var coinSize = 75;
var lastAnimationTime = 0;
var howLongUntilNextCoin = 1000;
var nextCoinOnScreen = 0;
function doDraw() {
var can = document.getElementById("myCanvas");
can.width = rW;
can.height = rH;
var context = can.getContext("2d");
//Erase the canvas
context.fillStyle = "#FFFFFF";
context.fillRect(0, 0, rW, rH);
if (new Date().getTime() - nextCoinOnScreen > 0) {
var newX = Math.floor(Math.random() * rW) + 1;
var newY = rH + 50;
var newCoin = {
x: newX,
y: newY
};
coinsOnScreen.push(newCoin);
nextCoinOnScreen = new Date().getTime() + howLongUntilNextCoin;
}
//Now draw the coins
if (lastAnimationTime != 0) {
var deltaTime = new Date().getTime() - lastAnimationTime;
var coinRisePixels = Math.floor((deltaTime * risingSpeed) / 1000);
var survivingCoins = [];
for (var i = 0; i < coinsOnScreen.length; i++) {
var coin = coinsOnScreen[i];
coin.y = coin.y - coinRisePixels;
//the stl variable controlls the alpha of the image
if (coin.y + 50 > 0) {
context.drawImage(coinImage, coin.x, coin.y);
//this coin is still on the screen, so promote it to the new array...
survivingCoins.push(coin);
}
}
coinsOnScreen = survivingCoins;
}
lastAnimationTime = new Date().getTime();
//Wait, and then call this function again to animate:
setTimeout(function() {
doDraw();
}, 30);
}
function setupClickHandler() {
var can = document.getElementById("myCanvas");
//Here is the onclick handler
can.onclick = function(e) {
var x = e.clientX;
var y = e.clientY;
var survivingCoins = [];
for (var i = 0; i < coinsOnScreen.length; i++) {
var coin = coinsOnScreen[i];
//check to see if this coin has been clicked...
if (x > coin.x && x < coin.x + coinSize && y > coin.y && y < coin.y + coinSize) {
//ths coin will disappear because it is not inserted into the new array...
console.log("Coin was clicked!! " + x + " " + y);
} else {
survivingCoins.push(coin);
}
}
coinsOnScreen = survivingCoins;
};
}
doDraw();
setupClickHandler();
function getCoinImage() {
var image = new Image(50, 50);
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAACXBIWXMAAAsTAAALEwEAmpwYAAAABGdBTUEAALGOfPtRkwAAACBjSFJNAAB6JQAAgIMAAPn/AACA6QAAdTAAAOpgAAA6mAAAF2+SX8VGAAAOWUlEQVR42mL8sYUBJ2BkhGAGKGZkQKUZYPz/QPo/gzwDE4MJEBswMDOoA7EUEAsD5bnAav8xfAfi9wx/GJ4x/GW4BWRfAuJTQLn7/xmBrP8Ie/9DzENh/4diXAAggFgYKAH/GCSBDg/4z84QyMjBYMbAysAPdDzEEf+g9H+Eh8GYCUqD5H8zfGX4wXCW4SfDBiB/HVDuIblOAQggRnJiBGipGiMLQzojF0Pkfy6gZ0DCv4HET7DjII7/C6T+IUKREeoJRmaoGaxAzAbFIP53hrf/vzKsBsbYDGAMXSQ1RgACiDSP/GfgBjqmlJGXIZeBk0EIaCkDwzeg+C+g34Ae+APEv75B6H9/MD3CCPQIEzANsAA9wc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O0v3QeSNcAOdsYocHNyIi/gAEIIFJXBx2CNmMSgbZlAS3Ugvf+YcM/jEhLP5jgqyfgIx7Ia0sYkZZKQX18D0jNBPJnQHs7RAOAACI1RhDjXsDaH0j5A1lRQLY9tHlIDvgJdPgxIL0CiNcCPfcWY20YETECEECUeASRbP4zaILaPUC+EZCtDmQD27oMvDhMBeWsh0BH3QTSF4BuOwBkX4LFCSO2RW5EeAQgwACQYpcXuHTdswAAAABJRU5ErkJggg==";
return image;
}
<canvas id="myCanvas"></canvas>

Scope issue with Coffeescript

I have some strange scope issue in Coffeescript.
I can't access to _this from the function #qr.callback, the _this doesn't seem to pass well. I never change this.imgName so the only reason that It doesn't work could be that _this is'nt passed well.
decode:(#callback) ->
_this= this
console.log 'before',_this.imgName
#qr= new QrCode()
#qr.callback= () ->
console.log "after:", _this.imgName
#qr.decode("data:image/png;base64,#{#base64Data}")
Edit:
I have tried using
console.log 'before',#imgName
#qr= new QrCode()
#qr.callback= () =>
console.log "after:", #imgName
#qr.decode("data:image/png;base64,#{#base64Data}")
But the output is the same
Edit2: QrCode code: This code comes from https://github.com/LazarSoft/jsqrcode. Howewer, as the source code of LazarSoft https://github.com/LazarSoft/jsqrcode/blob/master/src/qrcode.js did'nt contain a QrCode object that you could instantiate many times , I transformed the code to create many different instances of QrCode by creating a QrCode function instead of a global object qrcode.
QrCode= function ()
{
this.imagedata = null;
this.width = 0;
this.height = 0;
this.qrCodeSymbol = null;
this.debug = false;
this.sizeOfDataLengthInfo = [ [ 10, 9, 8, 8 ], [ 12, 11, 16, 10 ], [ 14, 13, 16, 12 ] ];
this.callback = null;
this.decode = function(src){
if(arguments.length==0)
{
var canvas_qr = document.getElementById("qr-canvas");
var context = canvas_qr.getContext('2d');
this.width = canvas_qr.width;
this.height = canvas_qr.height;
this.imagedata = context.getImageData(0, 0, this.width, this.height);
this.result = this.process(context);
if(this.callback!=null)
this.callback(this.result);
return this.result;
}
else
{
var image = new Image();
_this=this
image.onload=function(){
//var canvas_qr = document.getElementById("qr-canvas");
var canvas_qr = document.createElement('canvas');
var context = canvas_qr.getContext('2d');
var canvas_out = document.getElementById("out-canvas");
if(canvas_out!=null)
{
var outctx = canvas_out.getContext('2d');
outctx.clearRect(0, 0, 320, 240);
outctx.drawImage(image, 0, 0, 320, 240);
}
canvas_qr.width = image.width;
canvas_qr.height = image.height;
context.drawImage(image, 0, 0);
_this.width = image.width;
_this.height = image.height;
try{
_this.imagedata = context.getImageData(0, 0, image.width, image.height);
}catch(e){
_this.result = "Cross domain image reading not supported in your browser! Save it to your computer then drag and drop the file!";
if(_this.callback!=null)
_this.callback(_this.result);
return;
}
try
{
_this.result = _this.process(context);
}
catch(e)
{
// console.log('error:'+e);
_this.result = "error decoding QR Code";
}
if(_this.callback!=null)
_this.callback(_this.result);
}
image.src = src;
}
}
this.decode_utf8 = function ( s )
{
return decodeURIComponent( escape( s ) );
}
this.process = function(ctx){
var start = new Date().getTime();
var image = this.grayScaleToBitmap(this.grayscale());
//var image = this.binarize(128);
if(this.debug)
{
for (var y = 0; y < this.height; y++)
{
for (var x = 0; x < this.width; x++)
{
var point = (x * 4) + (y * this.width * 4);
this.imagedata.data[point] = image[x+y*this.width]?0:0;
this.imagedata.data[point+1] = image[x+y*this.width]?0:0;
this.imagedata.data[point+2] = image[x+y*this.width]?255:0;
}
}
ctx.putImageData(this.imagedata, 0, 0);
}
//var finderPatternInfo = new FinderPatternFinder().findFinderPattern(image);
var detector = new Detector(image,this);
var qRCodeMatrix = detector.detect();
/*for (var y = 0; y < qRCodeMatrix.bits.Height; y++)
{
for (var x = 0; x < qRCodeMatrix.bits.Width; x++)
{
var point = (x * 4*2) + (y*2 * this.width * 4);
this.imagedata.data[point] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0;
this.imagedata.data[point+1] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0;
this.imagedata.data[point+2] = qRCodeMatrix.bits.get_Renamed(x,y)?255:0;
}
}*/
if(this.debug)
ctx.putImageData(this.imagedata, 0, 0);
var reader = Decoder.decode(qRCodeMatrix.bits,this);
var data = reader.DataByte;
var str="";
for(var i=0;i<data.length;i++)
{
for(var j=0;j<data[i].length;j++)
str+=String.fromCharCode(data[i][j]);
}
var end = new Date().getTime();
var time = end - start;
console.log(time);
return this.decode_utf8(str);
//alert("Time:" + time + " Code: "+str);
}
this.getPixel = function(x,y){
if (this.width < x) {
throw "point error";
}
if (this.height < y) {
throw "point error";
}
point = (x * 4) + (y * this.width * 4);
p = (this.imagedata.data[point]*33 + this.imagedata.data[point + 1]*34 + this.imagedata.data[point + 2]*33)/100;
return p;
}
this.binarize = function(th){
var ret = new Array(this.width*this.height);
for (var y = 0; y < this.height; y++)
{
for (var x = 0; x < this.width; x++)
{
var gray = this.getPixel(x, y);
ret[x+y*this.width] = gray<=th?true:false;
}
}
return ret;
}
this.getMiddleBrightnessPerArea=function(image)
{
var numSqrtArea = 4;
//obtain middle brightness((min + max) / 2) per area
var areaWidth = Math.floor(this.width / numSqrtArea);
var areaHeight = Math.floor(this.height / numSqrtArea);
var minmax = new Array(numSqrtArea);
for (var i = 0; i < numSqrtArea; i++)
{
minmax[i] = new Array(numSqrtArea);
for (var i2 = 0; i2 < numSqrtArea; i2++)
{
minmax[i][i2] = new Array(0,0);
}
}
for (var ay = 0; ay < numSqrtArea; ay++)
{
for (var ax = 0; ax < numSqrtArea; ax++)
{
minmax[ax][ay][0] = 0xFF;
for (var dy = 0; dy < areaHeight; dy++)
{
for (var dx = 0; dx < areaWidth; dx++)
{
var target = image[areaWidth * ax + dx+(areaHeight * ay + dy)*this.width];
if (target < minmax[ax][ay][0])
minmax[ax][ay][0] = target;
if (target > minmax[ax][ay][1])
minmax[ax][ay][1] = target;
}
}
//minmax[ax][ay][0] = (minmax[ax][ay][0] + minmax[ax][ay][1]) / 2;
}
}
var middle = new Array(numSqrtArea);
for (var i3 = 0; i3 < numSqrtArea; i3++)
{
middle[i3] = new Array(numSqrtArea);
}
for (var ay = 0; ay < numSqrtArea; ay++)
{
for (var ax = 0; ax < numSqrtArea; ax++)
{
middle[ax][ay] = Math.floor((minmax[ax][ay][0] + minmax[ax][ay][1]) / 2);
//Console.out.print(middle[ax][ay] + ",");
}
//Console.out.println("");
}
//Console.out.println("");
return middle;
}
this.grayScaleToBitmap=function(grayScale)
{
var middle = this.getMiddleBrightnessPerArea(grayScale);
var sqrtNumArea = middle.length;
var areaWidth = Math.floor(this.width / sqrtNumArea);
var areaHeight = Math.floor(this.height / sqrtNumArea);
var bitmap = new Array(this.height*this.width);
for (var ay = 0; ay < sqrtNumArea; ay++)
{
for (var ax = 0; ax < sqrtNumArea; ax++)
{
for (var dy = 0; dy < areaHeight; dy++)
{
for (var dx = 0; dx < areaWidth; dx++)
{
bitmap[areaWidth * ax + dx+ (areaHeight * ay + dy)*this.width] = (grayScale[areaWidth * ax + dx+ (areaHeight * ay + dy)*this.width] < middle[ax][ay])?true:false;
}
}
}
}
return bitmap;
}
this.grayscale = function(){
var ret = new Array(this.width*this.height);
for (var y = 0; y < this.height; y++)
{
for (var x = 0; x < this.width; x++)
{
var gray = this.getPixel(x, y);
ret[x+y*this.width] = gray;
}
}
return ret;
}
}
var image = new Image();
_this=this
May lightning strike you, you're coding CoffeeScript too much! You forgot a var declaration here, so the ninth invocation of decode overwrites the global _this with its this instance - and when each decoding is finished, they all call the same callback.
Fix it by using
var _this = this;
or
var image = new Image,
_this = this;
or by using CoffeeScript everywhere :-)

Categories