javascript alert when canvas is clicked - javascript

I have a canvas on which I am making a menu screen for my game:
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);
ctx.font="30px monospace";
ctx.fillStyle = "black";
ctx.strokeText("click to begin",140,260);
When the user clicks "click to begin", I want it to progress to my game, but considering that I can't get the onclick working I just want it to alert that it has worked. So far (based off of tutorials and examples I have found) I have the following code:
mouse = (function (target) {
var isButtonDown = false;
c.addEventListener('mousedown', function () {
isButtonDown = true;
});
return {
isButtonDown: function () {
return isButtonDown;
}
};
}(document));
var isButtonDown = input.isButtonDown();
if (isbuttondown == true) {
alert("Mouse clicked");
}
This code does nothing when I run it. Could someone please explain to me how to get this working, or at least what I need to change?
Thanks in advance,
Riley

Here is a Solution.
Solution
I have removed the alert and instead used console.log. Check the console.
JS
canvas.addEventListener('click', function (evt) {
var mousePos = getMousePos(canvas, evt);
var message = 'Mouse Clicked at ' + mousePos.x + ',' + mousePos.y;
console.log(message);
}, false);
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
EDIT: Here is the same fiddle with Alert option. FIDDLE

Related

loading and editing pdf file or image using onsen and angularjs

I am tring to implement this example http://jsfiddle.net/vY2B4/1/ in my mobile applicaion
I am using onsen with angularjs to build the mobile application
what I need is to display the pdf file in onsen tab
<ons-page id="PDFPlam.html" ng-controller="pdfPlanCtrl">
<button class="button button-block button-positive"></button>
<canvas id="canvas" width="800" height="600">
Your browser does not support the canvas element.
</canvas>
</ons-page>
and this is my controller
angular.module('myApp').controller('pdfPlanCtrl',['$scope', function($scope) {
$scope.canvas ;
$scope.context
addEventListener('load', load, false);
function load(){
alert('loaded');
$scope.canvas = document.getElementById("canvas");
console.log('canvas is '+ $scope.canvas);
$scope.context = document.getElementById('canvas').getContext('2d');
var mountain = new Image();
mountain.onload = function() {
console.log('init pdf');
$scope.context.drawImage(this, 0, 0);
initPointCollection();
}
mountain.src = 'file:///storage/emulated/0/Android/data/com.example.helloworld/files/249_139.jpg';
}
var points = [];
// Determine where the user clicked, I believe I pulled this from elsewhere on StackOverflow a while ago.
function getCursorPosition(e) {
var mx, my;
if (e.pageX || e.pageY) {
mx = e.pageX;
my = e.pageY;
}
else {
mx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
my = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
mx -= canvas.offsetLeft;
my -= canvas.offsetTop;
return {x: mx, y: my};
}
// Once we have at least two points, draw a line between them.
function drawPath() {
context.beginPath();
for (var i = 0; i < points.length - 1; i++) {
context.moveTo(points[i]['x'], points[i]['y']);
context.lineTo(points[i+1]['x'], points[i+1]['y']);
context.stroke();
}
context.closePath();
}
// Listen for clicks, and redraw the map when they occur.
function initPointCollection() {
canvas.onclick = function(e) {
var point = getCursorPosition(e);
points.push(point);
if (points.length > 1) {
drawPath();
}
}
}
$scope.initPDFPlan = function() {
// Load up your image. Don't attempt to draw it until we know it's been loaded.
}
}]);
the problem that the Ioad function is not called so it is not work

Canvas moves using keyboard input but image does not

so I started with the basics adding canavs, css, javascript. should the image be in the html or javascript?
next i added a background color to the canvas. then i add canvas properties in javascript along with keyCodes. i got the image in with window.onload. after that i notice the canvas was moving but not the image.
var canvas = document.getElementById("app");
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
canvas.style.width = canvas.width + "px";
canvas.style.height = canvas.height + "px";
var keys = [];
window.addEventListener("keydown", function(e){
keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e){
delete keys[e.keyCode];
}, false);
function game(){
window.onload;
update();
render();
}
function update(){
if(keys[38]) img.y--;
if(keys[40]) img.y++;
if(keys[37]) img.x--;
if(keys[39]) img.x++;
}
function render(){
ctx.fillRect(img.x, img.y);
}
window.onload = function() {
var c=document.getElementById("app");
var ctx=c.getContext("2d");
var img=document.getElementById("chio");
ctx.drawImage(img,10,10);
};
setInterval(function(){
game();
}, 1000/30)
// > note: window.onload shows the images
#app{
background-color:#33ff00
}
<html>
<head>
<link href="app.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<canvas id="app" width=300 height=640></canvas>
<img id="chio" src="chio.png"/>
<script src="app.js"></script>
</body>
</html>
I'm lost at this point, please help me
I made some correction in "app.js" but I don't know what do you want exactly. If you wanted to move the image then this is a way.
var canvas = document.getElementById("app");
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
canvas.style.width = canvas.width + "px";
canvas.style.height = canvas.height + "px";
var keys = [];
var ctx;
var img;
var position = {x:0,y:0};
window.addEventListener("keydown", function(e){
keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e){
keys[e.keyCode] = false;
}, false);
function game(){
update();
render();
}
function update(){
if(keys[38]) position.y--;
if(keys[40]) position.y++;
if(keys[37]) position.x--;
if(keys[39]) position.x++;
}
function render(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img,position.x,position.y);
}
window.onload = function() {
var c=document.getElementById("app");
ctx=c.getContext("2d");
img=document.getElementById("chio");
};
setInterval(function(){
game();
}, 1000/30);
// > note: window.onload shows the images
There are a number of problems with the code you've given, the most problematic being that you're trying to access DOM elements in various places potentially before the document has loaded. This should all be done attached to the window.onload event you're already using.
Another issue is that you're declaring variables locally and initializing them, but elsewhere in your code you treat them as global variables and try to access them - generating more errors. These variables should be moved to the global scope.
You're also trying to modify some x/y attribute on the original <img> element to track its position on the canvas - this won't work. I'd move the position tracking into a JavaScript object with x/y properties.
Lastly, you're not calling the correct code to draw the image to the canvas in your render() function. I'd suggest clearing the canvas and redrawing the image with drawImage().
Putting all these suggestions to practice, your JavaScript becomes:
// Global variables for later use
var keys = [];
var canvas;
var ctx;
var img;
// Object to track image position on canvas
var imgPos = {
x: 0,
y: 0
}
window.addEventListener("keydown", function(e){
keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e){
delete keys[e.keyCode];
}, false);
function game(){
window.onload;
update();
render();
}
function update(){
if(keys[38]) imgPos.y--;
if(keys[40]) imgPos.y++;
if(keys[37]) imgPos.x--;
if(keys[39]) imgPos.x++;
}
function render(){
// Clear canvas and redraw image at new location
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img,imgPos.x,imgPos.y);
}
window.onload = function() {
// Initialize canvas
canvas = document.getElementById("app");
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
canvas.style.width = canvas.width + "px";
canvas.style.height = canvas.height + "px";
// Draw image to canvas
ctx=canvas.getContext("2d");
img=document.getElementById("chio");
ctx.drawImage(img,imgPos.x,imgPos.y);
// Start game loop
setInterval(function(){
game();
}, 1000/30);
};
Here's a JSFiddle to demonstrate. I've commented the code wherever I made significant changes to help you follow it better. Hope this helps! Let me know if you have any questions.

mouseclick event JavaScript doesn't work in Firefox

I made this piece of code for turning sound on/off in a game I'm making.
It works great with Google Chrome and IE. Proud as I was I gave the code to my friend who tried it on Firefox..
But he made me sad by saying it didn't work on Firefox...
I don't know why it doesn't work, can somebody tell me what's wrong or maybe what I have to change?
P.S.: "geluidknop" is Dutch for "soundbutton".
var audio = new Audio('Beep.mp3');
function playAudio() {
audio.play();
}
function pauseAudio() {
audio.pause();
audio.currentTime = 0;
}
window.addEventListener('keydown', playAudio);
audio.play();
function CanvasApp() {
'use strict'
var canvas = document.getElementById("canvas"),
style = window.getComputedStyle(canvas),
context = canvas.getContext("2d"),
source1 = "geluidaan.png",
source2 = "geluiduit.png",
click = false,
geluidknop = {x: 0, y: 0, width: 1024, height: 768};
geluidknop.aspect = geluidknop.height / geluidknop.width;
geluidknop.width = 500;
geluidknop.height = geluidknop.width * geluidknop.aspect;
canvas.width = parseInt(style.width, 10);
canvas.height = parseInt(style.height, 10);
var img = new Image();
img.onload = function () {
context.drawImage (img, geluidknop.x, geluidknop.y, geluidknop.width, geluidknop.height);
};
img.src = source1;
function changeImage() {
if (click) {
img.src = source2;
} else {
img.src = source1;
}
}
function MouseClick() {
var rect = canvas.getBoundingClientRect(),
x = event.clientX - rect.left,
y = event.clientY - rect.top;
if (x >= geluidknop.x && x <= geluidknop.x + geluidknop.width) {
if (y >= geluidknop.y && y <= geluidknop.y + geluidknop.height) {
if (click) {
click = false;
playAudio();
changeImage();
}else {
click = true;
pauseAudio();
changeImage();
}
}
}
context.save();
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);
context.restore();
}
canvas.addEventListener('click', MouseClick);
function restartAudio() {
audio.currentTime = 0;
audio.play();
}
audio.addEventListener('ended', restartAudio);
}
function WindowLoaded() {
'use strict';
CanvasApp();
}
window.addEventListener("load", WindowLoaded);
I think you forgot to pass event to your event handler function. Chrome will fill this in, but Firefox will not.
It should be:
function MouseClick(event) {}
This issue might not be your code, but more likley .mp3 support in firefox.
Dependant on the version of firefox he was using a .mp3 file might not be supported
check out the mozilla docs on audio support

Generating new canvas dynamically in javascript

I have a canvas that I can draw things what I want to do is generate new canvases dynamically when clicking a button.I've defined a generate function but it did not work
here is script
//<![CDATA[
window.addEventListener('load', function () {
// get the canvas element and its context
var canvas = document.getElementById('sketchpad');
var context = canvas.getContext('2d');
// create a drawer which tracks touch movements
var drawer = {
isDrawing: false,
touchstart: function (coors) {
context.beginPath();
context.moveTo(coors.x, coors.y);
this.isDrawing = true;
},
touchmove: function (coors) {
if (this.isDrawing) {
context.lineTo(coors.x, coors.y);
context.stroke();
}
},
touchend: function (coors) {
if (this.isDrawing) {
this.touchmove(coors);
this.isDrawing = false;
}
}
};
// create a function to pass touch events and coordinates to drawer
function draw(event) {
var type = null;
// map mouse events to touch events
switch(event.type){
case "mousedown":
event.touches = [];
event.touches[0] = {
pageX: event.pageX,
pageY: event.pageY
};
type = "touchstart";
break;
case "mousemove":
event.touches = [];
event.touches[0] = {
pageX: event.pageX,
pageY: event.pageY
};
type = "touchmove";
break;
case "mouseup":
event.touches = [];
event.touches[0] = {
pageX: event.pageX,
pageY: event.pageY
};
type = "touchend";
break;
}
// touchend clear the touches[0], so we need to use changedTouches[0]
var coors;
if(event.type === "touchend") {
coors = {
x: event.changedTouches[0].pageX,
y: event.changedTouches[0].pageY
};
}
else {
// get the touch coordinates
coors = {
x: event.touches[0].pageX,
y: event.touches[0].pageY
};
}
type = type || event.type
// pass the coordinates to the appropriate handler
drawer[type](coors);
}
// detect touch capabilities
var touchAvailable = ('createTouch' in document) || ('ontouchstart' in window);
// attach the touchstart, touchmove, touchend event listeners.
if(touchAvailable){
canvas.addEventListener('touchstart', draw, false);
canvas.addEventListener('touchmove', draw, false);
canvas.addEventListener('touchend', draw, false);
}
// attach the mousedown, mousemove, mouseup event listeners.
else {
canvas.addEventListener('mousedown', draw, false);
canvas.addEventListener('mousemove', draw, false);
canvas.addEventListener('mouseup', draw, false);
}
// prevent elastic scrolling
document.body.addEventListener('touchmove', function (event) {
event.preventDefault();
}, false); // end body.onTouchMove
}, false); // end window.onLoad
function generate(){
var newCanvas = document.createElement('canvas');
newCanvas.width = 400;
newCanvas.height = 400;
document.getElementById('container').appendChild(newCanvas);
ctx = newCanvas.getContext('2d');
}
//]]>
here is jsfiddle http://jsfiddle.net/regeme/WVUwn/
ps:drawing not displayed on jsfiddle however it works on my localhost I have totally no idea about it , anyway what I need is generate function , I did but I think I am missing something..
Any ideas? thanks..
Below is a function I wrote to dynamically create canvas.
If the canvas already exists (same ID) then that canvas is returned.
The pixelRatio parameter can be defaulted to 1. It's used for setting the correct size on retina displays (so for iPhone with Retina the value would be 2)
function createLayer(sizeW, sizeH, pixelRatio, id, zIndex) {
// *** An id must be given.
if (typeof id === undefined) {
return false;
}
// *** If z-index is less than zero we'll make it a buffer image.
isBuffer = (zIndex < 0) ? true : false;
// *** If the canvas exist, clean it and just return that.
var element = document.getElementById(id);
if (element !== null) {
return element;
}
// *** If no zIndex is passed in then default to 0.
if (typeof zIndex === undefined || zIndex < 0) {
zIndex = 0;
}
var canvas = document.createElement('canvas');
canvas.width = sizeW;
canvas.height = sizeH;
canvas.id = id;
canvas.style.width = sizeW*pixelRatio + "px";
canvas.style.height = sizeH*pixelRatio + "px";
canvas.style.position = "absolute";
canvas.style.zIndex = zIndex;
if (!isBuffer) {
var body = document.getElementsByTagName("body")[0];
body.appendChild(canvas);
}
return canvas;
}
Change the jsfiddle option
"onLoad"
to
"No Wrap - in <body>"
EDIT: See also similar question over here: Uncaught ReferenceError for a function defined in an onload function
JSFiddle options: http://doc.jsfiddle.net/basic/introduction.html#frameworks-and-extensions
This is the working update of your JSFIDDLE
javascript:
document.getElementById('generate').addEventListener('mousedown', generate, false);
I guess this is what you want.
I've just added an eventListener to your button in javascript code itself.
P.S.: I've also added black background color to canvas to show it on white background.

Paint Basic Line in Canvas [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
Now lines are drawn to something like a "fan", but I need the lines were drawn in a standard graphics editor. I am where there were mistakes in the transfer of coordinates in the function but I can not understand where
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
canvas.width = 640;
canvas.height = 480;
var posMouse = {};
posMouse.paint = false;
$('#myCanvas').mousedown(function (e)
{
posMouse.paint = true;
posMouse.x1 = e.pageX - this.offsetLeft;
posMouse.y1 = e.pageY - this.offsetTop;
$("#xPosMouseDown").text("? - down: " + posMouse.x1 + "; ");
$("#yPosMouseDown").text("Y - down: " + posMouse.y1 + "; ");
});
$('#myCanvas').mousemove(function (e)
{
if (posMouse.paint == false){return false;}
posMouse.x2 = e.pageX - this.offsetLeft;
posMouse.y2 = e.pageY - this.offsetTop;
context.beginPath();
context.moveTo(posMouse.x1, posMouse.y1);
context.lineTo(posMouse.x2, posMouse.y2);
context.stroke();
context.closePath();
$("#xPosMouseMove").text("? - move: " + posMouse.x2 + "; ");
$("#yPosMouseMove").text("Y - move: " + posMouse.y2 + "; ");
});
$('#myCanvas').mouseup(function (e)
{
posMouse.paint = false;
});
$('#myCanvas').mouseleave(function (e)
{
posMouse.paint = false;
});
Updated Demo
What the OP is asking for I believe is a way to show the tool and then draw on the canvas after. #John what you have to do is have a temporary canvas to show the tools, which you clear each time you move it. So I added a temp canvas to your code, and positioned it over the "actual" canvas. Now it shows the tool actions on the temp canvas, and draws the results on the canvas below.
$(document).ready(function(){
var canvas = document.getElementById("myCanvas"); // получаем элемент по идентификатору
var context = canvas.getContext("2d"); // определяем 2D (двумерный) контекст отрисовки
// Задаем ширину и высоту Canvas
canvas.width = 640; // ширина по умолчанию - 300
canvas.height = 480; // ширина по умочанию - 150
context = canvas.getContext('2d');
// Make a temporary canvas to show our draw operations on
var container = canvas.parentNode,
tempCanvas = document.createElement('canvas'),
tool = {};
tempCanvas.id = 'canvasTemp';
tempCanvas.width = canvas.width;
tempCanvas.height = canvas.height;
container.appendChild(tempCanvas);
tempCtx = tempCanvas.getContext("2d");
// End of temp code
var posMouse = {};
posMouse.paint = false;
$('#canvasTemp').mousedown(function (e)
{
posMouse.paint = true;
posMouse.x1 = e.pageX - this.offsetLeft;
posMouse.y1 = e.pageY - this.offsetTop;
$("#xPosMouseDown").text("Х - down: " + posMouse.x1 + "; ");
$("#yPosMouseDown").text("Y - down: " + posMouse.y1 + "; ");
});
$('#canvasTemp').mousemove(function (e)
{
if (posMouse.paint == false){
paintOnCanvas(tool);
return false;
}
tempCtx.clearRect(0,0,tempCanvas.width, tempCanvas.height);
posMouse.x2 = e.pageX - this.offsetLeft;
posMouse.y2 = e.pageY - this.offsetTop;
// Temporarily save the coords so we can draw on the actual canvas
tool.x1 = posMouse.x1;
tool.x2 = posMouse.x2;
tool.y1 = posMouse.y1;
tool.y2 = posMouse.y2;
tempCtx.beginPath();
tempCtx.moveTo(posMouse.x1, posMouse.y1);
tempCtx.lineTo(posMouse.x2, posMouse.y2);
tempCtx.stroke();
tempCtx.closePath();
$("#xPosMouseMove").text("Х - move: " + posMouse.x2 + "; ");
$("#yPosMouseMove").text("Y - move: " + posMouse.y2 + "; ");
});
$('#canvasTemp').mouseup(function (e){
paintOnCanvas(tool);
posMouse.paint = false;
});
$('#canvasTemp').mouseleave(function (e){
paintOnCanvas(tool);
posMouse.paint = false;
});
// This paints the result of the tool operation on the canvas underneath.
function paintOnCanvas(coords){
context.beginPath();
context.moveTo(coords.x1, coords.y1);
context.lineTo(coords.x2, coords.y2);
context.stroke();
context.closePath();
}
});
never used the canvas element myself, i can't really tell at glance where exactly your problem is.
but this is a nice example of creating a drawpane using canvas and jquery.
take a look at this:
http://motyar.blogspot.com/2010/04/drawing-on-web-with-canvas-and-jquery.html

Categories