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
Related
I've got a main.js calling a CanvasConstructor Class, in this one I make my canvas and manage the mouse for signing onto the canvas with different methods. That works!
Now I wanted to add methods to use it on smartphones (using ontouch events).
I can get only one position, which is not the actual position of my finger.
The ontouchmove() doesn't change the position either.
I tried to get my canvas by getElementById(), the problem was the same.
I assume that I've got some problems with getting the different contexts within my Class, so it's one part of the global problem.
The second problem is how to manage the ontouch events correctly.
(Sorry for my English and my JS skills, I try my best).
index.html:
<canvas class="canvas-style" id="canvas" width="200" height="70"></canvas>
main.js:
const canvas = new CanvasConstructor();
canvas.mouseConstructor();
canvas.touchConstructor();
/* I usually comment one of them to test each other */
canvas.js:
class CanvasConstructor{
constructor(){
this.color = "#000";
this.painting = false;
this.started = false;
this.width_brush = 2;
this.canvas = $("#canvas");
this.cursorX; this.cursorY;
this.restoreCanvasArray = [];
this.restoreCanvasIndex = 0;
this.context = this.canvas[0].getContext('2d');
this.context.lineJoin = 'round';
this.context.lineCap = 'round';
}
mouseConstructor(){
var self = this;
this.canvas.mousedown(function(e) {
this.painting = true;
this.cursorX = (e.pageX - this.offsetLeft);
this.cursorY = (e.pageY - this.offsetTop);
});
this.canvas.mouseup(function() {
this.painting = false;
this.started = false;
});
this.canvas.mousemove(function(e) {
if (this.painting) {
this.cursorX = (e.pageX - this.offsetLeft) - 10;
this.cursorY = (e.pageY - this.offsetTop) - 10;
self.drawLine(this.cursorX, this.cursorY);
}
});
self.reset();
}
touchConstructor(){
var self = this;
this.canvas[0].addEventListener('touchstart', function(e) {
e.preventDefault();
this.painting = true;
console.log("touchSTART!!");
this.cursorX = (e.pageX - this.offsetLeft);
this.cursorY = (e.pageY - this.offsetTop);
}, false);
this.canvas[0].addEventListener('touchend', function(e) {
e.preventDefault();
this.painting = false;
this.started = false;
}, false);
this.canvas[0].addEventListener('touchmove', function(e) {
if (this.painting) {
e.preventDefault();
this.cursorX = (e.pageX - this.offsetLeft);
this.cursorY = (e.pageY - this.offsetTop);
self.drawLine(this.cursorX, this.cursorY);
}
}, false);
self.reset();
}
drawLine(cursorX, cursorY) {
if (!this.started) {
this.context.beginPath();
this.context.moveTo(cursorX, cursorY);
this.started = true;
}
else {
this.context.lineTo(cursorX, cursorY);
this.context.strokeStyle = this.color;
this.context.lineWidth = this.width_brush;
this.context.stroke();
}
}
clear_canvas() {
this.context.clearRect(0,0, this.canvas.width(), this.canvas.height());
}
reset(){
var self = this;
$("#reset").click(function() {
self.clear_canvas();
});
}
}
When you touch the canvas you get the ontouchstart(), onctouchend() and ontouchmove() functions, but it doesn't draw because I can't get the actual position of the touching.
Please explain me how to do it correctly.
I have update the touchConstructor function as follow.
touchConstructor(){
var self = this;
this.canvas[0].addEventListener('touchstart', function(e) {
e.preventDefault();
this.painting = true;
console.log("touchSTART!!");
var pageX = e.touches[0].pageX; //to get pageX value in touch devices
var pageY = e.touches[0].pageY; //to get pageY value in touch devices
this.cursorX = (pageX - this.offsetLeft);
this.cursorY = (pageY - this.offsetTop);
}, false);
this.canvas[0].addEventListener('touchend', function(e) {
e.preventDefault();
this.painting = false;
this.started = false;
}, false);
this.canvas[0].addEventListener('touchmove', function(e) {
if (this.painting) {
e.preventDefault();
var pageX = e.touches[0].pageX; //to get pageX value in touch devices
var pageY = e.touches[0].pageY; //to get pageY value in touch devices
this.cursorX = (pageX - this.offsetLeft);
this.cursorY = (pageY - this.offsetTop);
self.drawLine(this.cursorX, this.cursorY);
}
}, false);
self.reset();
}
Below is a script which defines two functions that draw 4 rectangular buttons and 1 circular button respectively. I am trying to implement specific Hover and Click functionality into the buttons (as described in the script alerts) but I am at a bit of a loss as to how to do this. I tried calling the makeInteractiveButton() functions on each click but this caused a lot of odd overlap and lag. I want the script to do the following:
If the circular button is hovered, I would like it's fillColour to change and if it is clicked I would like it to change again to the colours described in the code (#FFC77E for hover, #FFDDB0 for clicked). This should only happen for the duration of the hover or click.
HTML:
<html lang="en">
<body>
<canvas id="game" width = "750" height = "500"></canvas>
<script type='text/javascript' src='stack.js'></script>
</body>
</html>
JavaScript:
var c=document.getElementById('game'),
canvasX=c.offsetLeft,
canvasY=c.offsetTop,
ctx=c.getContext('2d')
elements = [];
c.style.background = 'grey';
function makeInteractiveButton(x, strokeColor, fillColor) {
ctx.strokeStyle=strokeColor;
ctx.fillStyle=fillColor;
ctx.beginPath();
ctx.lineWidth=6;
ctx.arc(x, 475, 20, 0, 2*Math.PI);
ctx.closePath();
ctx.stroke();
ctx.fill();
elements.push({
arcX: x,
arcY: 475,
arcRadius: 20
});
}
b1 = makeInteractiveButton(235, '#FFFCF8', '#FFB85D');
c.addEventListener('mousemove', function(event) {
x=event.pageX-canvasX; // cursor location
y=event.pageY-canvasY;
elements.forEach(function(element) {
if (x > element.left && x < element.left + element.width &&
y > element.top && y < element.top + element.height) { // if cursor in rect
alert('Rectangle should undergo 5 degree rotation and 105% scale');
}
else if (Math.pow(x-element.arcX, 2) + Math.pow(y-element.arcY, 2) <
Math.pow(element.arcRadius, 2)) { // if cursor in circle
alert('Set b1 fillColour to #FFC77E.');
}
});
}, false);
c.addEventListener('click', function(event) {
x=event.pageX-canvasX; // cursor location
y=event.pageY-canvasY;
elements.forEach(function(element) {
if (x > element.left && x < element.left + element.width &&
y > element.top && y < element.top + element.height) { // if rect clicked
alert('Move all cards to centre simultaneously.');
}
else if (Math.pow(x-element.arcX, 2) + Math.pow(y-element.arcY, 2) <
Math.pow(element.arcRadius, 2)) { // if circle clicked
alert('Set b1 fillColour to #FFDDB0.');
}
});
}, false);
One way is keep all element data and write a hitTest(x,y) function but when you have a lot of complex shapes its better to use a secondary canvas to render element with their ID instead of their color in it and the color of x,y in second canvas is ID of hitted element, I should mention that the second canvas is'nt visible and its just a gelper for get the hitted element.
Github Sample:
https://siamandmaroufi.github.io/CanvasElement/
Simple implementation of hitTest for Rectangles :
var Rectangle = function(id,x,y,width,height,color){
this.id = id;
this.x=x;
this.y=y;
this.width = width;
this.height = height;
this.color = color || '#7cf';
this.selected = false;
}
Rectangle.prototype.draw = function(ctx){
ctx.fillStyle = this.color;
ctx.fillRect(this.x,this.y,this.width,this.height);
if(this.selected){
ctx.strokeStyle='red';
ctx.setLineDash([5,5]);
ctx.lineWidth = 5;
ctx.strokeRect(this.x,this.y,this.width,this.height);
}
}
Rectangle.prototype.hitTest=function(x,y){
return (x >= this.x) && (x <= (this.width+this.x)) &&
(y >= this.y) && (y <= (this.height+this.y));
}
var Paint = function(el) {
this.element = el;
this.shapes = [];
}
Paint.prototype.addShape = function(shape){
this.shapes.push(shape);
}
Paint.prototype.render = function(){
//clear the canvas
this.element.width = this.element.width;
var ctx = this.element.getContext('2d');
for(var i=0;i<this.shapes.length;i++){
this.shapes[i].draw(ctx);
}
}
Paint.prototype.setSelected = function(shape){
for(var i=0;i<this.shapes.length;i++){
this.shapes[i].selected = this.shapes[i]==shape;
}
this.render();
}
Paint.prototype.select = function(x,y){
for(var i=this.shapes.length-1;i>=0;i--){
if(this.shapes[i].hitTest(x,y)){
return this.shapes[i];
}
}
return null;
}
var el = document.getElementById('panel');
var paint = new Paint(el);
var rectA = new Rectangle('A',10,10,150,90,'yellow');
var rectB = new Rectangle('B',150,90,140,100,'green');
var rectC = new Rectangle('C',70,85,200,70,'rgba(0,0,0,.5)');
paint.addShape(rectA);
paint.addShape(rectB);
paint.addShape(rectC);
paint.render();
function panel_mouseUp(evt){
var p = document.getElementById('panel');
var x = evt.x - p.offsetLeft;
var y = evt.y - p.offsetTop;
var shape = paint.select(x,y);
if(shape){
alert(shape.id);
}
//console.log('selected shape :',shape);
}
function panel_mouseMove(evt){
var p = document.getElementById('panel');
var x = evt.x - p.offsetLeft;
var y = evt.y - p.offsetTop;
var shape = paint.select(x,y);
paint.setSelected(shape);
}
el.addEventListener('mouseup',panel_mouseUp);
el.addEventListener('mousemove',panel_mouseMove);
body {background:#e6e6e6;}
#panel {
border:solid thin #ccc;
background:#fff;
margin:0 auto;
display:block;
}
<canvas id="panel" width="400px" height="200px" >
</canvas>
just click or move over the shapes
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
I would like an image to move to the left if the mouse is to the left of the screen and to the right if the mouse to the right of the screen, using javascript, here is the code I have so far:
var dirx = 0;
var spdx = 35;
var imgLeftInt;
var imgTopInt;
var imgHeight;
var imgWidth;
var divWidth;
var divHeight;
var t;
var tempX;
var tempY;
So I'm pretty sure I'm not missing any variables...
function animBall(on) {
imgLeftInt = parseInt(document.images['logo'].style.left);
imgTopInt = parseInt(document.images['logo'].style.top);
imgHeight = parseInt(document.images['logo'].height);
imgWidth = parseInt(document.images['logo'].width);
divWidth = parseInt(document.images['container'].width);
if (tempX > 779){
dirx = 1;
}
else if(tempX < 767){
dirx = 2;
}
else {
spdx = 0;
}
So if tempX, which should be the x coordinate of the mouse location, is bigger than 779, which is the halfway point of the div tag, the image should go right. If it's less than that, it should go left, and otherwise, the speed should be zero, as in it should stay still.
if(dirx == 1){
goRight();
} else if(dirx == 2) {
goLeft();
}
}
function getMouseXY(e) {
tempX = e.clientX;
tempY = e.clientY;
}
I found hundreds of different ways to get the mouse location, but this was off W3C so I assume it works.
function goRight() {
document.images['logo'].style.left = imgLeftInt+spdx +"px";
if (imgLeftInt > (divWidth-imgWidth)){
dirx = 2;
spdx= 20;
}
}
function goLeft() {
document.images['logo'].style.left = (imgLeftInt-spdx) +"px";
if (imgLeftInt < 5){
dirx = 1;
spdx= 20;
}
}
</script>
So that's my whole script.
<div id="container" onmousemove="getMouseXY(event);" width="1546" height="423">
Start Animation Stop Animation <br />
<img src="http://qabila.tv/images/logo_old.png" style="position:absolute;left:10px;top:20px;" id="logo" />
</div>
I left the dependency on the mouse location to the very end so the animation script works fine (or at least worked, unless I broke something trying to get it to read the mouse location).
Any ideas what I'm doing wrong??
If it's any help, I've hosted the code here.
I went to your link and tried debugging your code. I get an error on line 21 because your document has no "container" image ("container" is a div).
At the start of your question, you said you wanted to know mouse position relative to center of "screen". For that, you'd probably want to use window.innerWidth instead of the width attribute that you set on your div.
Well that needed a whole load of work, anyway, I have done some of it for you and you can now see things partially working, but you will need to play with it on jsfiddle. Perhaps you can now open some specific questions regarding getting this to work.
<div id="container" width="1546" height="423"> <a id="start" href="#">Start Animation</a> <a id="stop" href="#">Stop Animation</a>
<br />
<img src="http://qabila.tv/images/logo_old.png" style="position:absolute;left:10px;top:20px;" id="logo" />
</div>
/*jslint sub: true, maxerr: 50, indent: 4, browser: true */
/*global */
(function () {
"use strict";
var start = document.getElementById("start"),
stop = document.getElementById("stop"),
container = document.getElementById("container"),
logo = document.getElementById("logo"),
dirx = 0,
spdx = 35,
imgLeftInt,
imgTopInt,
imgHeight,
imgWidth,
divWidth,
divHeight,
t,
tempX,
tempY;
function getMouseXY(e) {
tempX = e.clientX;
tempY = e.clientY;
}
function goRight() {
logo.style.left = imgLeftInt + spdx + "px";
if (imgLeftInt > (divWidth - imgWidth)) {
dirx = 2;
spdx = 20;
}
}
function goLeft() {
logo.style.left = (imgLeftInt - spdx) + "px";
if (imgLeftInt < 5) {
dirx = 1;
spdx = 20;
}
}
// attribute on unused
function animBall(on) {
imgLeftInt = parseInt(logo.style.left, 10);
imgTopInt = parseInt(logo.style.top, 10);
imgHeight = parseInt(logo.height, 10);
imgWidth = parseInt(logo.width, 10);
divWidth = parseInt(container.width, 10);
if (tempX > 779) {
dirx = 1;
} else if (tempX < 767) {
dirx = 2;
} else {
spdx = 0;
}
if (dirx === 1) {
goRight();
} else if (dirx === 2) {
goLeft();
}
}
function startAnim() {
t = setInterval(animBall, 80);
}
start.addEventListener("click", startAnim, false);
function stopAnim() {
clearInterval(t);
}
stop.addEventListener("click", stopAnim, false);
container.addEventListener("mousemove", getMouseXY, false);
}());
Why don't you usee the html5 canvas and gee.js
Here's the js fiddle result (it may take a while to load, but that's fault of jsfiddle, the script will load much faster once on your website): http://jsfiddle.net/wLCeE/7/embedded/result/
and here's the much simpler code to make it work:
var g = new GEE({
width: 500,
height: 423,
container: document.getElementById('canvas')
});
var img = new Image(); // Create new img element
img.onload = function () {
demo(g)
};
img.src = 'http://qabila.tv/images/logo_old.png'; // Set source path
function demo(g) {
var style = "left"
g.draw = function () {
if (g.mouseX > g.width / 2 && style == "left") styleRight()
else if (g.mouseX < g.width / 2 && style == "right") styleLeft()
}
function styleLeft() {
style = "left"
g.ctx.clearRect(0, 0, g.width, g.height)
g.ctx.drawImage(img, 0, 0)
}
function styleRight() {
style = "right"
g.ctx.clearRect(0, 0, g.width, g.height)
g.ctx.drawImage(img, g.width - img.width, 0)
}
}
Currently I'm creating a sheet of graph paper with the canvas object in HTML5. I'm able to create the canvas as well as fill in the selected areas with a color by finding the x/y position. Unfortunately I'm having some troubles using the jQuery mousemove method to display a pop-up of the information selected for the square.
Here's my code:
Canvas Creation/Layout:<br>
<script type="text/javascript">
var canvas;
var context;
var color;
var state;
var formElement;
var number = 0;
function showGrid()
{
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
context.lineWidth=0.5;
context.strokeStyle='#999999';
lineSpacing=10;
var xPos = 0;
var yPos = 0;
var numHorizontalLines = parseInt(canvas.height/lineSpacing);
var numVerticalLines = parseInt(canvas.width/lineSpacing);
state = new Array(numHorizontalLines);
for (var y = 0; y < numHorizontalLines; ++y)
{
state[y] = new Array(numVerticalLines);
}
for(var i=1; i<=numHorizontalLines;i++)
{
yPos=i*lineSpacing;
context.moveTo(0,yPos);
context.lineTo(canvas.width,yPos);
context.stroke;
}
for(var i=1; i<=numVerticalLines; i++)
{
xPos=i*lineSpacing;
context.moveTo(xPos,0);
context.lineTo(xPos,canvas.height);
context.stroke();
}
}
function fill(s, gx, gy)
{
context.fillStyle = s;
context.fillRect(gx * lineSpacing, gy * lineSpacing, lineSpacing, lineSpacing);
if(s != null)
{
}
}
function getPosition(e)
{
var x = new Number();
var y = new Number();
var canvas = document.getElementById("canvas");
if (e.pageX || e.pageY)
{
x = e.pageX;
y = e.pageY;
}
else
{
x = e.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
x -= canvas.offsetLeft;
y -= canvas.offsetTop;
var gx = Math.floor((x / lineSpacing));
var gy = Math.floor((y / lineSpacing));
state[gy][gx] = true;
fill(color, gx, gy);
addNumber();
}
HTML:
<div class="graphpaper" id="graphpaper" onclick="getPosition(event)" style="width:956px; height:1186px;">
<img src="images/PosterBorder_Top.png" align="right"/>
<img src="images/posterBorder_left.png" align="left" valign="top"/>
<canvas id ="canvas" width = "920" height = "1160" align="left">
</canvas>
</div>
<!-- HIDDEN / POP-UP DIV -->
<div id="pop-up">
<h3>Pop-up div Successfully Displayed</h3>
<p>
This div only appears when the trigger link is hovered over.
Otherwise it is hidden from view.
</p>
</div>
jQuery for Pop-Up display:
$('#canvas').mousemove(function(event){
console.log("Here I am!");
$('div#pop-up').show().appendTo('body');
});
Any suggestions? I'm obviously missing something but from what I've done this should work I believe.