I have a form element in my HTML page that currently retrieves the toDataURL() from one canvas(canvas2) and draws the image into a second canvas(outputCanvas). What I need is for that onclick event to retrieve the canvas image and use that image in this function. As of now Im able to manually save the canvas image as a .png and then hard-code the file into this function, but I need this all to happen when the button is clicked. Im a newb at .js but I can handle pseudo-code if its easier to explain, but please be specific. The following draw() needs to be handled when the click occurs. I have the listener below that should call the draw().
function init () {
canvas = document.getElementById('anotherCanvas');
ctx = canvas.getContext('2d');
draw ();
}
function draw() {
img = new Image();
img.src = 'recursed1.png';
fr1 = makeFrame(ctx,makeVect(400,0), makeVect(400, 0), makeVect(0, 400));
img.onload = function(){
ctx.save();
newPainter = cornerSplit(imagePainter,5);
newPainter(fr1);
ctx.restore();
ctx.save();
newPainter(flipHorizLeft(fr1));
ctx.restore();
ctx.save();
newPainter(flipVertDown(fr1));
ctx.restore();
ctx.save();
newPainter(flipVertDown(flipHorizLeft(fr1)));
}
The following is currently independent of the above, I can only get the above function to work if I manually save & hard-code the image created in an independent canvas (canvas2). I need the two to work together. The HTML element:
<input type="button" id="recImage" value="Recurse Image">
var formElement = document.getElementById("createImageData");
formElement.addEventListener('click', createImageDataPressed, false);
function createImageDataPressed(e) {
var imageDataDisplay = document.getElementById("imageDataDisplay");
imageDataDisplay.value = canvas2.toDataURL();
var newImagewindow.open(canvas2.toDataURL(),
"canvasImage","right=300,top=400,width="canvas2.width + ",height=" +
canvas2.height + ",toolbar=0,resizable=0");
}
The above is my most recent attempt, it doesn't work... Nothing is set in stone, and If there is a better route than what Im attempting please let me know. this work in progress may help you understand what Im trying to do
From my understanding, you want init and data to be called when formElement is clicked, right?
Just add a call to init and data in createImageDataPressed or add some more click handlers to formElement.
Related
I am having trouble trying to resize the uploaded image on to my html for project. When I searched for a solution. The site https://www.w3schools.com/tags/canvas_drawimage.asp gave me an idea but I can't seem to wrap my head about the script. Am I misunderstanding something about the script?
<javascript>
function uploadForegroundImage(){
fileInput = document.getElementById("foregroundImageUpload");
image = new Image(fileInput);
image.onload = function() {
var c = document.getElementById("foregroundImageCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById(fileInput);
ctx.drawImage(img, 10, 10, 600, 400);
}
}
</javascript>
The code provided should work. If you are getting an error, make sure to load it from a URL that you have access to, or select it using an HTML input tag. Also I'm not aware of a "javascript" tag, it should be changed to "script"
I have an upload photo button on my website which uploads jpeg and png format files on the database.As well as it shows the photo on the website after successful completion.
After successful completion, ajax success calls the after_success function which has the response data as its parameter.
Function Looks like this:
function after_success(data){
}
Response Data Looks like:
<img src="uploads/56dda66be0181.png">
Whatever image comes up from this response I was trying to draw it on the canvas.
My Solution:
var canv=document.getElementById("output");
var ctx=canv.getContext("2d");
var canimg=($('img',data));
ctx.drawImage(canimg,10,10);
But this didn't seem to work.How do i get the image on this canvas element?
Note:
Using Div element and jquery .html() it does show the image inside the Div element.
Ok, if I understand correctly, from response of an upload you'll get an image tag, you want to draw the same image on to a canvas with the id output.
Breaking down -
1. you gave to get the image url from the src of the img tag you are getting as response.
2. You have to draw it on to output
var after_success = function(data){
$('.someHiddenDiv').append(data);//append the response data to some div which is invisible. This is just to get jQuery to access the element as dom.
var img = new Image();//well initialize a new image
//on load of the image draw it on to canvas
img.onload = function(){
var canvas = document.getElementById('output');
var ctx = canvas.getContext('2d');
ctx.drawImage(img,10,10);//same as what you have done
};
img.src = $('.someHiddenDiv').find('img').attr('src');//get source from the image tag
}
This should work!
function after_success(data){
$('#hiddendiv').html(data);
var img=new Image();
img.src=$('#hiddendiv').find('img').attr('src');
$('#hiddendiv').hide();
var canv=document.getElementById("output");
var ctx=canv.getContext("2d");
img.onload= function () {
ctx.drawImage(img,10,10);
}
This is what i did to achieve the same.Thanks to #anubhab.Gave me a fair Idea as to how to do this.Just tweaked his code a bit.
I am new to HTML 5 and JS for iPhone. In my application, I was succeeded to get touch points from the canvas by the following code(this is inside my game.js class):
canvas.addEventListener("click", mouseClickEvent, false);
function mouseClickEvent(e) {
alert("Clicked x= "+e.layerX+" and clicked y= "+e.layerY);
}
and I am displaying an object (hole) from the game.js class as:
var hole = new Image();
hole.onload = function() {
ctx.drawImage(hole,135,215,50,50);
}
hole.src = 'images/hole.png';
Now what I need is to:
1) Move the hole object to the touched position (like animating/moveto).
2) Add a click listener to the hole (I tried canvas.addEventListener, but not worked).
I've searched a lot. But not able to find a proper solution :(
Some tutorials said to: remove and redraw the object to move it. But I've several images on my screen, with different shapes.
Pls, pls help me to solve this...
Your touch events can be done like this:
var hole = {x: 0, y: 0};
var touchEvents = function(e){
e.preventDefault();
if(e.targetTouches) e = e.targetTouches[0]; // since i like to test with a mouse, but still have it work with touch devices.
hole.x=e.clientX;
hole.y=e.clientY;
};
canvas.onmousemove=touchEvents;
canvas.ontouchmove=touchEvents;
canvas.ontouchstart=touchEvents;
This was quickly converted from my js1k entry, the variable names are short, but maybe you can get a few hints: http://jsfiddle.net/9J25N/
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.
I am trying to load an image inside a function, but the image is not showing on the screen. There are no console errors so i don't know why it will not work.
Code:
var canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
var score = 0;
var menuImg = new Image();
menuImg.src = "images/Startscreen.png";
gamemenu();
//The menu screen
function gamemenu(){
ctx.drawImage(menuImg,0,0);
}
The image should draw when the function is called but it does not, any help?
Loading an image is an asynchronous process so you need to add an event handler for the "load" event.
menuImg = new Image();
menuImg.addEventListener("load", function () {
gamemenu();
}, false);
I deal with this on a regular basis in my projects since we make heavy use of canvas and sprite rendering.
Update: Here's MDN's page about this topic.