How to generate 2d canvas from console to div - javascript

My code I have so far will generate into console.log. When I hit F12 it will display an img right there in the console.
How can I make it appear inside a div or somewhere more user appropriate than the console?
I tried making a <div class = "mylog"> to appropriate it inside canvas but I'm new sure how to code that together either.
Any suggestions & help would be super awesome!
I hope my question is straight forward.
(function(console) {
console.image = function(url) {
var image = document.createElement('img'),
canvas = document.createElement('canvas'),
canvasCtx = canvas.getContext('2d'),
//more code here//
})(console);
window.onload = function() {
console.image()
);
}

We will need to see more code to be any help because it seems that you're directly placing the function inside the console as an image. This gets rendered as 2d, and a canvas but will output only to console. You need to redo the code or show us more context to give you a better idea of what to change.

Related

Displaying image from Javascript to Processing.js canvas

So, I'm trying to programmatically add an image to my canvas, from a Javascript function :
// Spawn function
var spawnWrapper = function() {
myCanvas = Processing.getInstanceById('mycanvas');
// myCanvas.ellipse(50,50,50,50); // works fine here too
myImage = myCanvas.loadImage('pegman.png');
myCanvas.image(myImage,0,0);
};
The same successive calls in console works :
Also, there are no errors mentioned on the console.
I'm really stuck there and would appreciate any help ;-)
I suspect that you might be missing the preload directive.
This directive regulates image preloading, which is required when
using loadImage() or requestImage() in a sketch. Using this directive
will preload all images indicated between quotes, and comma separated
if multiple images are used, so that they will be ready for use when
the sketch begins running.
I hope that helps. I'm curious as to why you're using processing.js instead of P5.js?
Good luck.

Trying to dynamically generate chart inside a Bootstrap modal, getting offsetWidth Error

I am using chartjs which is HTML5 based library, to dynamically draw a chart inside a Bootstrap modal body. Everything is fine and I can see the correct data and label array has been passed, and canvas HTML node has been created, but I am getting this error:
Uncaught TypeError: Cannot read property 'offsetWidth' of undefined
I thought maybe I am calling this function too early:
new Chart(--> HTML node <--).get(0).getContext("2d").Bar(--> data <--);
so I put it in setTimeout() block to call the function after like 2 seconds of appending canvas HTML node, but I am still getting that error and not able to see the chart.
Here is the complete code (github, Dropbox) and here is the part I am calling the chart libraray:
document.getElementById("modalBody").appendChild(canvasElement);
setTimeout(function () {
var ctx = document.getElementsByTagName("canvas")[0];
var myNewChart = new Chart(ctx).get(0).getContext("2d").Bar(finalData);
return finalData;
}, 2000);
I managed to get this working in Plunkr.
The basics of what I changed for both contextualizeForType2() and contextualizeForType3() are as follows:
The correct way to instantiate the bar chart component is using the 2D context for the canvas element you appended. In code, you have new Chart(ctx.getContext('2d')).Bar(finalData); after the var ctx = ... line. However, because the modal hasn't been shown yet, it will have a height and width of 0.
To have the chart use the correct height and width, you should bind to the shown.bs.modal event that gets triggered once the modal has finished animating in. Inside that event handler is where you create the chart. The tricky part comes because you have two different questions reusing the same modal. So I added an extra namespace of .typeX, which I unregister my events for when the modal gets hidden.
I know that second point is confusing, but hopefully the code clears it up:
var ctx = document.getElementsByTagName("canvas")[0];
$('#myModal').on({
'shown.bs.modal.type2': function() {
new Chart(ctx.getContext("2d")).Bar(finalData);
},
'hidden.bs.modal.type2': function() {
this.off('.type2');
}
});
This means that once the modal gets hidden, these two functions won't get run again when the same modal is shown for the other type. Additionally, you won't be creating more charts than you need, due to adding a new handler every time the button is clicked.
Alternative method
I had a further play and found that I could refactor the code into a single function that can be called from both contextualizeForType2() and contextualizeForType3(), passing in the finalData. This has the advantage of leaving all the canvas and chart initialisation code in one place, simplifying your large functions somewhat and making it easier to maintain.
The function is:
function showModalChart(data) {
var canvasElement = document.createElement("CANVAS");
canvasElement.setAttribute("width", "400");
canvasElement.setAttribute("height", "400");
document.getElementById("modalBody").appendChild(canvasElement);
var ctx = document.getElementsByTagName("canvas")[0];
$('#myModal').off('.modalchart').on('shown.bs.modal.modalchart', function () {
new Chart(ctx.getContext('2d')).Bar(data);
});
}

how to save DIV as Image with canvas2image with extension

I have done the following code to convert HTML Content(DIV) to save as Image (JPEG, PNG,GIF Etc) with below code.
<pre>
html2canvas($(".mainbox"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
Canvas2Image.saveAsImage(canvas);
$("#FinalImage").append(canvas);
}
});
</pre>
I have also included html2canvas.js,base64.js and canvas2image.js in my page. At the end Image is shown in #FinalImage DIV and browser ask me to save it in my drive up to now all are working fine.
Now the question is name of the saved image has no Extension, every time I need to go to the image and assign the Extension(".jpg",".png" etc...). Is there any solution to set extension by default when user saves from the browser.
Thanks in advance.
I have done same functionality for capturing signature. This is different from your approach. but this code snippet may help you. plz comment if u need whole source code.
var canvas = document.getElementById(<canvas element id>)// get canvas element
var dataURL = canvas.toDataURL("image/png");// convert to img, specify extension
document.getElementById(<new image id>).src = dataURL; // write as an image
In line two I specified png.there you can change the extension of image. Hope it helps

Assistance with HTML5 Canvas and JS displaying images on it please?

I'm making an Android game, in HTML5 and Javascript, I am part of the way there, but have hit something that has stumped me, My JS file and my Html file were working together, to draw on the canvas etc, but now I'm trying to draw an image on the canvas, nothing is being displayed, I know the img function is being found, as, alert (img);, works so it's just lost on me. (currently this is copied from a book I was given at college, and it's identical, the JS has been verified in JSHint and passes, so I'm lost) also, please be quite simple, I'm pretty new to JS but have used html for a long time, and this just has to be a simple game for a college assignment.
My HTML code is
<canvas id="game" width="1024" height="600">Sorry, your browser does not support this</canvas>
and my JS is:
function init() {
var elem = document.getElementById('game');
var canvas = elem.getContext('2d');
var img = document.createElement('img');
img.setAttribute('src', 'http://www.minkbooks.com/content/snow.jpg');
img.addEventListener("load", function() {
canvas.drawImage(img, 20, 20);
alert(canvas);
});
}
addEventListener("load", init);
and here it is on JSfiddle: http://jsfiddle.net/xw8m7/
This answer is based on your jsfiddle. You are executing your javascript code as soon as it is loaded. Depending on where your code is located in the html, the canvas element might not be loaded yet, and that would prevent your code from loading the image into the canvas element, and you would still get the alert.
In JSFiddle, you need to set the option of running your code "onDomready". That means that the JavaScript won't run until everything has been loaded (your canvas element). After changing that in your jsfiddle, your function loaded the image into the canvas just fine.
Update:
Based on your comment about XDK, I found a bit of example code and modified it. Original source: https://software.intel.com/en-us/node/493117
document.addEventListener("intel.xdk.device.ready",function(){
init();
},false);

Jquery and canvas code not working on same external file

I have been mucking about with a little bit coding using jquery and canvas (not together).
I have an external javascript file and in it contains;
$(document).ready(function() {
/*
NAME CHOOSER
*/
var carl = ['Sha', 'Shads', 'Cai', 'Moon', 'Sun', 'Staffy',];
var rosie = ['Mum',];
var prev;
$('button').click(function() {
prev = $('h2').text();
$('h2').empty().text(carl[Math.floor(Math.random() * carl.length)] + rosie[Math.floor(Math.random() * rosie.length)]).after('<p>' + prev + '</p>');
});
});
I also have some inline javascript which is for the canvas element;
<script>
var canvas = document.getElementById('draw');
if(canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, 800, 500);
}
</script>
When separated by using inline javascript for the canvas and an external file for the jquery everything works fine and as expected.
When adding the inline canvas javascript to the external file the canvas element is not working but the jquery is. The javascript is loaded after the canvas element as my external javascript is linked just before the closing body tag and furthermore if I remove all jquery from the external file the canvas element begins to work again.
Why is this?
Thanks
EDIT
I have also now tried putting the canvas code inside jquerys document ready function and outside of it and it is still not working. I have wrapped the canvas code in an anonymous function still to no avail and have even tried selecting the canvas element with jquery itself like below;
var canvas = $('canvas')[0];
But it still doesn't want to know. Putting the canvas code before all the jquery then the canvas code executes but the jquery doesn't, I really am baffled! It doesn't bother me keeping it seperate but I would like to know why it is happening.
Thanks again.
This simple problems could be noted if you use the Browser Console. That's it! You can open the console pressing Ctrl+Shift+J:
In home page:
Error: Uncaught ReferenceError: $ is not defined
Solution: Link jQuery in your source
In namechooser page:
Error: Uncaught TypeError: Cannot read property 'getContext' of null
The problem:
You are trying to manipulate a div as it was a canvas, and you can't get the context of a div element. So this is your HTML:
<div id="wrap">
<h1>PORTFOLIO PROJECT :)</h1>
<button>Click here to generate a company name!</button>
</div>
Solution:
Change <div> for <canvas>
How to avoid future problems like this?
Use the browser console, that's it!
Ok, if I combine the code you have, above, it should look something like this: (see my jsFiddle for full context : http://jsfiddle.net/mori57/TqamB/ )
$(document).ready(function () {
/*
NAME CHOOSER
*/
var carl = ['Sha', 'Shads', 'Cai', 'Moon', 'Sun', 'Staffy'];
var rosie = ['Mum'];
var prev;
$('button').click(function () {
prev = $('h2').text();
$('h2').empty().text(carl[Math.floor(Math.random() * carl.length)] + rosie[Math.floor(Math.random() * rosie.length)]).after('<p>' + prev + '</p>');
});
var canvas = document.getElementById('draw');
if(canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, 800, 500);
}
});
And, running within the context of jsFiddle, this works perfectly.
So, either you're not combining the two scripts properly (putting the canvas outside the document-ready block, for example, or somehow missing a closing brace), or there's something else amiss in your script file or markup.

Categories

Resources