Please help me:
create clickable regions in the canvas below that I can assign onmousedown= events to. I know how to do this with invisible DIVs, but I think there is a more elegant way to do it in canvas that I don't know.
when I click one of the regions, want to pass an image name to a function so that it changes the image being displayed to another image, and then changes it back onmouseup.
if you show me just one region and one mousedown/mouseup example I can do the rest...thanks.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<canvas id="myCanvas" width="506" height="319" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
};
img.src="firstImage.gif";
</script>
/////////HERE NEED/////////
CREATE CLICKABLE REGION <region>
<region>
onmousedown=changeCanvasImage(secondImage.gif) //change image on click
onmouseup=changeCanvasImage(firstImage.gif) /change it back when done
</region>
</body>
</html>
The canvas element can fire events but graphical elements within the canvas cannot. To do this you'll either need to implement it yourself by detecting the position of the mouse on the canvas when it is clicked and relating the value to something in your canvas, or using one of the many canvas libraries available which will handle the detection for you.
Related
I am using fabricjs 1.5 and I am stuck on 1 thing. I want to show the preview of the canvas to the user on click of button and I can not come up with a proper solution. Some things that crossed my mind are:
Save the current canvas state and then render it on the other canvas
Create a temporary image save function and then show this image
But I want to know if there is any specific function in the fabricjs that can help me achieve this. I did some R&D and could not find anything and hence I have not tried anything.
Use canvas.toDataURL() to get the image of canvas, and set it to image source.
DEMO
var canvas = new fabric.Canvas('c');
canvas.add(new fabric.Circle({radius:100,fill:'red'}))
function setPreview(){
document.getElementById('img').src = canvas.toDataURL();
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<button onclick="setPreview()">Preview</button><br>
<canvas id="c" width="200" height="200" style="border:1px solid #ccc"></canvas>
<br>
<img id='img'/>
I know this question has already been asked several times, however, I haven't
found a solution yet.
I want to take an image, rotate it and put it in a HTML canvas, to do this I'm using another canvas in which I rotate the image, this part works well, however, when I try to take the image from the second canvas using .toDataUrl, it returns a blank image. The code is the following
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<canvas id=canvas height="400" width="400" style="border: 10px solid orange"></canvas>
<canvas id=canvasTransform height="183" width="183" style="border: 10px solid orange"></canvas>
<script type="text/javascript">
//this is the canvas in which I want to put the rotated image
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
//and I use this one to rotate it
var canvasTransform=document.getElementById('canvasTransform');
var contextTransform=canvasTransform.getContext("2d");
var image=new Image(46,183);
image.onload=function(){
contextTransform.drawImage(image,0,0);
}
image.src="Fireball.png";
console.log(image.src);
//Now I rotate the context
contextTransform.rotate(-0.25*Math.PI);
//After doing this, I can see the rotated image in the second canvas, however, the following line returns a blank image
var rotatedImageURL=canvasTransform.toDataURL();
console.log(rotatedImageURL);
//Finally, this part isn't wornking since I just draw a blank image
var rotatedImage=new Image();
rotatedImage.onload=function(){
context.drawImage(rotatedImage,0,0);
}
rotatedImage.src=rotatedImageURL;
</script>
</body>
</html>
I have been stuck here for a while, so any help is appreciated. Thanks in advance!
You likely need to wait until after drawing the image before calling toDataURL. The fireball is only drawn after the image is loaded but the rotate (and everything after that) is called right after registering the onload event handler (but before it has actually loaded).
I'm trying to add an eventlistener to a picture so once clicked it takes me to a different page, at the moment I have it taking me to the next page but not when I click the picture, but when I click anywhere on the canvas
Responding to canvas click events
Oops, it looks like your question was cut off! On your next question, be sure not to hit the “Enter” key—instead of starting a new line in your question, you will immediately post your partially written question (don’t worry…we’ve all done it).
And Nick, “Welcome to stackoverflow” – it really is full of answers!
Norguard is right about the canvas not being able to keep track of which image you clicked on. Think of canvas as an artist's easel and you are painting images on that easel. Yes, the easel contains the images, but the easel has no way of knowing where you drew any image.
To keep your life simple while you’re learning, try starting with having just 1 image per canvas (yes, you can have as many canvas elements as you have images).
If you want to start with 1 image per canvas, here is code and a Fiddle: http://jsfiddle.net/m1erickson/KGKYg/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var img=new Image();
img.onload=function(){
canvas.width=img.width;
canvas.height=img.height;
ctx.drawImage(img,0,0);
}
img.src="http://dl.dropbox.com/u/139992952/coffee.png";
canvas.addEventListener("click", function (e) { alert("use your linke totake me away...!"); });
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
[Edit: Responding to keyboard events]
Here's how you can listen for user keypresses and respond to them:
// listen for keyboard events
window.addEventListener('keydown',keyIsDown,true);
// process the keystrokes
function keyIsDown(event){
switch (event.keyCode) {
case 38:
// "UP" was pressed, do UP stuff
break;
case 40:
// "DOWN" was pressed, do DOWN stuff
break;
}
}
You can't do this simply, and there's no event listener that will let you.
1) listen for the click on the canvas
2) keep a reference to the image object that you drew... ...as in, know its canvas coordinates, by keeping reference in a separate object:
var canvas_img = {
x : 250,
y : 300,
data : my_img,
width : my_img.width,
height : my_img.height
};
3) on click of the canvas, manually calculate whether a collision happened between where the click happened on the canvas, and where the image is on the canvas.
Here is my code:
<body>
<canvas id="myCanvas" width="1100" height="600" style="border:1px solid #c3c3c3; cursor:move">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=new Image();
img.src="image.jpg";
img.id="im";
img.onload = function(){
ctx.drawImage(img,0,0,100,100);
autoRun();
};
function autoRun(){
ctx.clearRect(0, 0, 1100,600);
img.id="im";
ctx.drawImage(img,Math.floor((Math.random()*1000)+1),Math.floor((Math.random()*500)+1),70,70);
setTimeout('autoRun()',1000);
}
</script>
</body>
Here I am using the random method for setting the X and Y coordinates hence the image will move dynamically will move the area of canvas ...
setTimeout('autoRun()',1000);
The above line will call the autorun function javascript for every sec and that function will clear the canvas and redraw the image with new coordinates....
Now i would like to get the id of the image when we click on it. How can I do that?
EDIT- This would not work !
Should this work for you ? Or are there any other complications ?
//This would bind to all image, but you can use
//other jquery selectors to select your perticular
//image
$('img').click(function(){
var my_id = $(this).attr('id');
return false;
});
EDIT
"..The image itself is not available in the DOM, you just created it temporarily to draw it into the canvas. So the canvas holds the content of the image, the image itself is not in the DOM"
Select image within canvas with jQuery
I think you should segment the shape of your image (defining its boundary pixels) and then check if when you click inside the canvas, the point selected (the mouse position when clicking) is inside the image shape.
This can be a solution for your problem.
the desired behavior is when the document loads, canvas draws image 0. when the invisible div is clicked, canvas draws image 1, on mouseup or mouseout, it reverts back to image 0.
I left the css out because I got that working...just need to know what I'm doing wrong with the javascript function. right now it doesn't display anything, not even the first image.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function imgChange(imagePath)
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
};
img.src=imagePath; <!-- I THINK THIS IS WRONG?
</script>
</head>
<body>
<canvas id="myCanvas" width="506" height="319"
onload="imgChange('0.gif')" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<div id="button1" onMouseDown="imgChange('1.gif')" onMouseUp="imgChange('0.gif')" onMouseOut="imgChange('0.gif')"></div>
<div id="key2"></div>
</body>
</html>
your code is missing an ending block
function imgChange(imagePath) {
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
};
img.src=imagePath;
}
The last '}' is missing
JavaScript looks good. But you can't click on an invisible div. Make the div visible and try.
Be aware of same origin policy too. Image path should be in your domain. If you are running in localhost you might need to have a local HTTP server.