hi guys I need some help with my canvas, I try differeent ways to make it work in mobile devices but I can't.
I try to launch the methodes that I create to start and stop the click events. But I think is not the rigth way.
class Canvas {
constructor(emplacement, btnEffacer, btnCroix) {
//btn pour effacer et afficher
this.btnCroix = document.querySelector(".fermeture")
this.btnEffacer = document.querySelector(btnEffacer);
// emplacement du canvas
this.canvas = document.querySelector(emplacement);
this.cont = this.canvas.getContext("2d");
//quelques variables
this.signer = false;
this.vide = true
this.canvas.width = 190;
this.canvas.height = 120;
this.cont.lineWidth = 2;
this.cont.strokeStyle = "#000";
//les evenements
//comencer a dessigner
this.canvas.addEventListener("touchstart", this.touchstart.bind(this), false);
this.canvas.addEventListener("touchmove", this.touchmove.bind(this), false);
this.canvas.addEventListener("touchend", this.touchend.bind(this), false);
this.canvas.addEventListener("mousedown", this.demarrer.bind(this));
//arreter de dessigner
this.canvas.addEventListener("mouseup", this.arreter.bind(this));
//le trece du dessin
this.canvas.addEventListener("mousemove", this.dessiner.bind(this));
//effacer le dessin
this.btnCroix.addEventListener("click", this.effacer.bind(this));
this.btnEffacer.addEventListener("click", this.effacer.bind(this));
}
//les methodes
touchstart(e) {
e.preventDefault()
const touche = e.touches[0]
this.demarrer(e)
}
touchmove(e) {
e.preventDefault()
const touche = e.touches[0]
this.dessiner(e)
}
touchend(e) {
e.preventDefault()
this.arreter(e)
}
demarrer(e) {
this.signer = true;
this.vide = false
this.dessiner(e);
}
arreter(e) {
this.signer = false;
this.cont.beginPath();
}
dessiner(e) {
if (!this.signer) return;
this.cont.lineTo(e.offsetX, e.offsetY);
this.cont.stroke();
this.cont.beginPath();
this.cont.moveTo(e.offsetX, e.offsetY);
}
effacer() {
this.cont.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.vide = true
}
If you can explain me how it works and help me with the code, it will be great.
thanks for your help
It seems like you may be the keyword 'on' before your touch events.
The following three lines in your code:
this.canvas.addEventListener("touchstart", this.touchstart.bind(this), false);
this.canvas.addEventListener("touchmove", this.touchmove.bind(this), false);
this.canvas.addEventListener("touchend", this.touchend.bind(this), false);
Should actually be:
this.canvas.addEventListener("ontouchstart", this.touchstart.bind(this), false);
this.canvas.addEventListener("ontouchmove", this.touchmove.bind(this), false);
this.canvas.addEventListener("ontouchend", this.touchend.bind(this), false);
https://www.w3schools.com/jsref/obj_touchevent.asp
This page has a canvas you can draw on with your finger or mouse:
<!doctype html>
<html><head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
</head><body>
<canvas id='thecanvas' width='700' height='1000' style='touch-action:none;border:1px solid #cccccc;'></canvas>
<script>
let canvas = document.getElementById('thecanvas');
function canvas_read_mouse(canvas, e) {
let canvasRect = canvas.getBoundingClientRect();
canvas.tc_x1 = canvas.tc_x2;
canvas.tc_y1 = canvas.tc_y2;
canvas.tc_x2 = e.clientX - canvasRect.left;
canvas.tc_y2 = e.clientY - canvasRect.top;
}
function on_canvas_mouse_down(e) {
canvas_read_mouse(canvas, e);
canvas.tc_md = true;
}
function on_canvas_mouse_up(e) {
canvas.tc_md = false;
}
function on_canvas_mouse_move(e) {
canvas_read_mouse(canvas, e);
if (canvas.tc_md && (canvas.tc_x1 !== canvas.tc_x2 || canvas.tc_y1 !== canvas.tc_y2)) {
let ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(canvas.tc_x1, canvas.tc_y1);
ctx.lineTo(canvas.tc_x2, canvas.tc_y2);
ctx.stroke();
}
}
function canvas_read_touch(canvas, e) {
let canvasRect = canvas.getBoundingClientRect();
let touch = event.touches[0];
canvas.tc_x1 = canvas.tc_x2;
canvas.tc_y1 = canvas.tc_y2;
canvas.tc_x2 = touch.pageX - document.documentElement.scrollLeft - canvasRect.left;
canvas.tc_y2 = touch.pageY - document.documentElement.scrollTop - canvasRect.top;
}
function on_canvas_touch_start(e) {
canvas_read_touch(canvas, e);
canvas.tc_md = true;
}
function on_canvas_touch_end(e) {
canvas.tc_md = false;
}
function on_canvas_touch_move(e) {
canvas_read_touch(canvas, e);
if (canvas.tc_md && (canvas.tc_x1 !== canvas.tc_x2 || canvas.tc_y1 !== canvas.tc_y2)) {
//alert(`${canvas.tc_x1} ${canvas.tc_y1} ${canvas.tc_x2} ${canvas.tc_y2}`);
let ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(canvas.tc_x1, canvas.tc_y1);
ctx.lineTo(canvas.tc_x2, canvas.tc_y2);
ctx.stroke();
}
}
canvas.addEventListener('mousedown', (e) => { on_canvas_mouse_down(e) }, false);
canvas.addEventListener('mouseup', (e) => { on_canvas_mouse_up(e) }, false);
canvas.addEventListener('mousemove', (e) => { on_canvas_mouse_move(e) }, false);
canvas.addEventListener('touchstart', (e) => { on_canvas_touch_start(e) }, false);
canvas.addEventListener('touchend', (e) => { on_canvas_touch_end(e) }, false);
canvas.addEventListener('touchmove', (e) => { on_canvas_touch_move(e) }, false);
</script>
</body></html>
Related
I want to visualize audio that is coming in from webrtc(JSSIP). I used WebAudio, connected analyzer node and it seems to be working fine with Firefox.
In chrome browser, thing seems to be not working. I can listen to the audio in Chrome but am not able to visualize it, it doesn't throw any error. I checked the array, it shows -Infinity.
What could be the reason for it? How can I visualize in chrome?
console.log(dataArray);
>> Float32Array(512) [-Infinity, -Infinity, -Infinity, -Infinity, -Infinity, -Infinity, -Infinity, …]
Code for the same
const AudioContext = window.AudioContext || window.webkitAudioContext;
var audioElement;
var audioCtx;
var analyser;
const canvas = document.getElementById("visualizer");
const canvasCtx = canvas.getContext("2d");
canvas.width = window.innerWidth - 50;
canvas.height = canvas.width / 2;
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var drawVisual;
const socketUrl = "wss://website.com:8089/ws";
var ua;
var configuration = {
sockets: [],
'uri': "",
'password': "",
'username': "",
'register': true
};
var room = "";
var session;
var callOptions = {
'mediaConstraints': { 'audio': true, 'video': false },
'pcConfig': {
'iceServers': [
{ 'urls': ['stun:stun.l.google.com:19302'] },
]
}
};
const callBtn = document.getElementById('call-btn');
const hangupBtn = document.getElementById('hangup-btn');
hangupBtn.setAttribute('disabled','disabled');
var initAudioElement = function () {
audioElement = new window.Audio();
audioElement.autoplay = true;
audioElement.crossOrigin = "anonymous";
document.body.appendChild(audioElement);
}
var audioCtxInit = function () {
try {
audioCtx = new AudioContext();
analyser = audioCtx.createAnalyser();
} catch (e) {
alert('Web audio not supported.');
}
var audioTrack = audioCtx.createMediaElementSource(audioElement);
audioTrack.connect(analyser);
analyser.connect(audioCtx.destination);
}
var initializeJsSIP = function () {
if (ua) {
ua.stop();
ua = null;
}
try {
const socket = new JsSIP.WebSocketInterface(socketUrl);
JsSIP.debug.disable('JsSIP:*'); // Debugger
configuration.sockets = [socket];
configuration.uri = "";
ua = new JsSIP.UA(configuration);
} catch (error) {
console.log(error);
}
ua.on("connecting", () => {
console.log('UA "connecting" event');
});
ua.on("connected", () => {
console.log('UA "connected" event');
});
ua.on("disconnected", () => {
console.log('UA "disconnected" event');
});
ua.on("registered", (data) => {
console.log('UA "registered" event', data);
});
ua.on("unregistered", () => {
console.log('UA "unregistered" event');
});
ua.on("registrationFailed", (data) => {
console.log('UA "registrationFailed" event', data);
});
ua.on("newRTCSession", ({ originator, session: rtcSession, request: rtcRequest }) => {
console.log('UA "newRTCSession" event');
// identify call direction
if (originator === "local") {
const foundUri = rtcRequest.to.toString();
const delimiterPosition = foundUri.indexOf(";") || null;
console.log(`foundUri: ${foundUri}`);
} else if (originator === "remote") {
const foundUri = rtcRequest.from.toString();
const delimiterPosition = foundUri.indexOf(";") || null;
console.log(`foundUri: ${foundUri}`);
}
if (session) { // hangup any existing call
session.terminate();
}
session = rtcSession;
session.on("failed", (data) => {
console.log('rtcSession "failed" event', data);
session = null;
});
session.on("ended", () => {
console.log('rtcSession "ended" event');
session = null;
});
session.on("accepted", () => {
console.log('rtcSession "accepted" event');
[
audioElement.srcObject,
] = session.connection.getRemoteStreams();
var playPromise = audioElement.play();
if (typeof playPromise !== "undefined") {
playPromise
.then(() => {
console.log("playing");
visualize();
})
.catch((error) => {
console.log(error);
});
}
});
});
ua.start();
}
function visualize() {
var WIDTH = canvas.width;
var HEIGHT = canvas.height;
analyser.fftSize = 2 ** 10;
var bufferLength = analyser.frequencyBinCount;
var dataArray = new Float32Array(bufferLength);
canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
function draw() {
drawVisual = requestAnimationFrame(draw);
analyser.getFloatFrequencyData(dataArray);
canvasCtx.fillStyle = 'rgb(0, 0, 0)';
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
var barWidth = (WIDTH / bufferLength) * 2.5;
var barHeight;
var x = 0;
for (var i = 0; i < bufferLength; i++) {
barHeight = (dataArray[i] + 140) * 2;
canvasCtx.fillStyle = 'rgb(' + Math.floor(barHeight + 100) + ',50,50)';
canvasCtx.fillRect(x, HEIGHT - barHeight / 2, barWidth, barHeight / 2);
x += barWidth + 1;
}
}
draw();
}
callBtn.addEventListener('click', function () {
callBtn.setAttribute('disabled','disabled');
hangupBtn.removeAttribute('disabled');
if (!audioCtx) {
audioCtxInit();
}
// check if context is in suspended state (autoplay policy)
if (audioCtx.state === 'suspended') {
audioCtx.resume();
}
ua.call(room, callOptions);
});
hangupBtn.addEventListener('click', function () {
callBtn.removeAttribute('disabled');
hangupBtn.setAttribute('disabled', 'disabled');
if (drawVisual) {
canvasCtx.clearRect(0, 0, canvas.width, canvas.height);
canvasCtx.fillStyle = 'rgb(0, 0, 0)';
canvasCtx.fillRect(0, 0, canvas.width, canvas.height);
window.cancelAnimationFrame(drawVisual);
drawVisual = null;
}
ua.terminateSessions();
});
window.onload = function () {
readyStateTimer = setInterval(function () {
if (document.readyState === "complete") {
clearInterval(readyStateTimer);
initAudioElement();
initializeJsSIP();
}
}, 500);
}
window.onbeforeunload = function () {
audioElement.parentNode.removeChild(this.audioElement);
delete audioElement;
if (ua) {
ua.stop();
ua = null;
}
};
For some reason in my game i can detect collisions but bodies are actually not colliding they are passing through.
This is how i create player:
function createPlayer () {
player = game.add.sprite(200, 200, 'playerimg');
player.anchor.setTo(0.5,0.5);
game.physics.p2.enableBody(player, true);
player.body.data.shapes[0].sensor = true;
game.camera.follow(player);
player.body.onBeginContact.add(player_coll, this);
console.log(player.body)
}
player_coll function fires perfectly fine on collision.
var tree_object = function (id, type, startx, starty, value) {
this.id = id;
this.posx = startx;
this.posy = starty;
this.tree = game.add.sprite(this.posx, this.posy, 'tree');
this.tree.type = 'tree';
this.tree.id = id;
game.physics.p2.enableBody(this.tree, true);
this.tree.body_size = 10;
this.tree.body.data.gravityScale = 0;
this.tree.body.data.shapes[0].sensor = true;
}
function player_coll(body,test){
if(body.sprite.type=="tree"){
console.log(body)
console.log("collided with tree")
}
}
My preload function:
function preload(){
game.stage.disableVisibilityChange = true; // mouse browserdan çıkınca uyutma.2 ekran test için.
game.scale.scaleMode = Phaser.ScaleManager.RESIZE;
game.world.setBounds(0, 0, gameProperties.gameWidth,
gameProperties.gameHeight);
//Fizik için P2JS kullanıcaz.
game.physics.startSystem(Phaser.Physics.P2JS);
//fizik dünyasının sınırlarını yaratır.(duvarlar)
game.physics.p2.setBoundsToWorld(true, true, true, true, true)
//Y nin yerçekimini 0 a eşitle böylece yere düşmeyecek.
game.physics.p2.gravity.y = 0;
// Yerçekimini tamamen kapat.
game.physics.p2.applyGravity = false;
game.physics.p2.enableBody(game.physics.p2.walls, false);
game.load.image('playerimg', '/assets/player.png');
game.load.image('background', 'assets/lake.png');
game.load.image("wood", "/assets/wood.png");
game.load.image("tree", "/assets/tree.png");
// Collision(çarpma) detectionu aç.
game.physics.p2.setImpactEvents(true);
}
As you see in the picture why they are passing through ?
I am making a javascript game, using Canvas. It works well superficially, but "Uncaught TypeError: game_state.Update is not a function" keeps going. I cannot know the reason for all day...How can I solve the problem?
error image1, error image2
Suspected files are below.
gfw.js
function onGameInit()
{
document.title = "Lion Travel";
GAME_FPS = 30;
debugSystem.debugMode = true;
//resourcePreLoading
resourcePreLoader.AddImage("/.c9/img/title_background.png");
resourcePreLoader.AddImage("/.c9/img/title_start_off.png");
resourcePreLoader.AddImage("/.c9/img/title_start_on.png");
resourcePreLoader.AddImage("/.c9/img/title_ranking_off.png");
resourcePreLoader.AddImage("/.c9/img/title_ranking_on.png");
resourcePreLoader.AddImage("/.c9/img/game_background_sky.png");
soundSystem.AddSound("/.c9/background.mp3", 1);
after_loading_state = new TitleState();
game_state = TitleState;
setInterval(gameLoop, 1000 / GAME_FPS);
}
window.addEventListener("load", onGameInit, false);
GameFramework.js
window.addEventListener("mousedown", onMouseDown, false);
window.addEventListener("mouseup", onMouseUp, false);
var GAME_FPS;
var game_state;
function onMouseDown(e)
{
if(game_state.onMouseDown != undefined)
game_state.onMouseDown(e);
// alert("x:" + inputSystem.mouseX + " y:" + inputSystem.mouseY);
}
function onMouseUp(e)
{
if(game_state.onMouseUp != undefined)
game_state.onMouseUp(e);
}
function ChangeGameState(nextGameState)
{
if(nextGameState.Init == undefined)
return;
if(nextGameState.Update == undefined)
return;
if(nextGameState.Render == undefined)
return;
game_state = nextGameState;
game_state.Init();
}
function GameUpdate()
{
timerSystem.Update();
**game_state.Update();**
debugSystem.UseDebugMode();
}
function GameRender()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
game_state.Render();
if(debugSystem.debugMode)
{
Context.fillStyle = "#ffffff";
Context.font = '15px Arial';
Context.textBaseline = "top";
Context.fillText("fps: "+ frameCounter.Lastfps, 10, 10);
}
}
function gameLoop()
{
game_state = after_loading_state;
GameUpdate();
GameRender();
frameCounter.countFrame();
}
RS_Title.js
function TitleState()
{
this.imgBackground = resourcePreLoader.GetImage("/.c9/img/title_background.png");
this.imgButtonStartOff = resourcePreLoader.GetImage("/.c9/img/title_start_off.png");
this.imgButtonStartOn = resourcePreLoader.GetImage("/.c9/img/title_start_on.png");
this.imgButtonRankingOff = resourcePreLoader.GetImage("/.c9/img/title_ranking_off.png");
this.imgButtonRankingOn = resourcePreLoader.GetImage("/.c9/img/title_ranking_on.png");
soundSystem.PlayBackgroundMusic("/.c9/background.mp3");
return this;
}
TitleState.prototype.Init = function()
{
soundSystem.PlayBackgroundMusic("/.c9/background.mp3");
};
TitleState.prototype.Render = function()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
Context.drawImage(this.imgBackground, 0, 0);
//drawing button
if(inputSystem.mouseX > 170 && inputSystem.mouseX < 170+220
&& inputSystem.mouseY > 480 && inputSystem.mouseY < 480+100)
{
Context.drawImage(this.imgButtonStartOn, 170, 480);
this.flagButtonStart = true;
}
else
{
Context.drawImage(this.imgButtonStartOff, 170, 480);
this.flagButtonStart = false;
}
if(inputSystem.mouseX > 420 && inputSystem.mouseX < 420+220
&& inputSystem.mouseY > 480 && inputSystem.mouseY < 480+100)
{
Context.drawImage(this.imgButtonRankingOn, 420, 480);
this.flagButtonRanking = true;
}
else
{
Context.drawImage(this.imgButtonRankingOff, 420, 480);
this.flagButtonRanking = false;
}
};
TitleState.prototype.Update = function()
{
};
TitleState.prototype.onMouseDown = function()
{
if(this.flagButtonStart)
ChangeGameState(new PlayGameState());
after_loading_state = PlayGameState;
game_state = PlayGameState;
if(this.flagButtonRanking)
ChangeGameState();
};
RS_PlayGame.js
function PlayGameState()
{
this.imgBackgroundSky = resourcePreLoader.GetImage("/.c9/img/game_background_sky.png");
}
PlayGameState.prototype.Init = function()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
Context.drawImage(this.imgBackgroundSky, 0, 0);
};
PlayGameState.prototype.Render = function()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
Context.drawImage(this.imgBackgroundSky, 0, 0);
};
PlayGameState.prototype.Update = function()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
Context.drawImage(this.imgBackgroundSky, 0, 0);
};
As mentioned by the others, in the onMouseDown method you are assigning after_loading_state and game_state to PlayGameState which is a function and not an object. So later on when you want to access the Update method, it simply doesn't exist, because it is defined over the object prototype and not the function. You might want to do something like this so that you also avoid instantiating (calling) PlayGameState multiple times:
game_state = new PlayGameState();
ChangeGameState(game_state);
after_loading_state = game_state;
I am a javascript function to copy paste an image from the clipboard to HTML canvas, futher i also have a function to let the user draw(highlight) on the image pasted on the canvas. However, the drawing tool function seems to override the copy paste function as it is anonymous. I need help to make these two functions operate.
this is my function to copy from clipboard.
function CLIPBOARD_CLASS(canvas_id, autoresize) {
alert("BLAH");
var _self = this;
var canvas = document.getElementById(canvas_id);
var ctx = document.getElementById(canvas_id).getContext("2d");
var ctrl_pressed = false;
var reading_dom = false;
var text_top = 15;
var pasteCatcher;
var paste_mode;
//handlers
document.addEventListener('keydown', function (e) {
_self.on_keyboard_action(e);
}, false); //firefox fix
document.addEventListener('keyup', function (e) {
_self.on_keyboardup_action(e);
}, false); //firefox fix
document.addEventListener('paste', function (e) {
_self.paste_auto(e);
}, false); //official paste handler
//constructor - prepare
this.init = function () {
//if using auto
if (window.Clipboard)
return true;
pasteCatcher = document.createElement("div");
pasteCatcher.setAttribute("id", "paste_ff");
pasteCatcher.setAttribute("contenteditable", "");
pasteCatcher.style.cssText = 'opacity:0;position:fixed;top:0px;left:0px;';
pasteCatcher.style.marginLeft = "-20px";
pasteCatcher.style.width = "10px";
document.body.appendChild(pasteCatcher);
document.getElementById('paste_ff').addEventListener('DOMSubtreeModified', function () {
if (paste_mode == 'auto' || ctrl_pressed == false)
return true;
//if paste handle failed - capture pasted object manually
if (pasteCatcher.children.length == 1) {
if (pasteCatcher.firstElementChild.src != undefined) {
//image
_self.paste_createImage(pasteCatcher.firstElementChild.src);
}
}
//register cleanup after some time.
setTimeout(function () {
pasteCatcher.innerHTML = '';
}, 20);
}, false);
}();
//default paste action
this.paste_auto = function (e) {
paste_mode = '';
pasteCatcher.innerHTML = '';
var plain_text_used = false;
if (e.clipboardData) {
var items = e.clipboardData.items;
if (items) {
paste_mode = 'auto';
//access data directly
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") !== -1) {
//image
var blob = items[i].getAsFile();
var URLObj = window.URL || window.webkitURL;
var source = URLObj.createObjectURL(blob);
this.paste_createImage(source);
}
}
e.preventDefault();
}
else {
//wait for DOMSubtreeModified event
//https://bugzilla.mozilla.org/show_bug.cgi?id=891247
}
}
};
//on keyboard press -
this.on_keyboard_action = function (event) {
k = event.keyCode;
//ctrl
if (k == 17 || event.metaKey || event.ctrlKey) {
if (ctrl_pressed == false)
ctrl_pressed = true;
}
//c
if (k == 86) {
if (document.activeElement != undefined && document.activeElement.type == 'text') {
//let user paste into some input
return false;
}
if (ctrl_pressed == true && !window.Clipboard)
pasteCatcher.focus();
}
};
//on kaybord release
this.on_keyboardup_action = function (event) {
k = event.keyCode;
//ctrl
if (k == 17 || event.metaKey || event.ctrlKey || event.key == 'Meta')
ctrl_pressed = false;
};
//draw image
this.paste_createImage = function (source) {
var pastedImage = new Image();
pastedImage.onload = function () {
if (autoresize == true) {
//resize canvas
canvas.width = pastedImage.width;
canvas.height = pastedImage.height;
}
else {
//clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
ctx.drawImage(pastedImage, 0, 0);
};
pastedImage.src = source;
};
}
This my drawing tool function
if (window.addEventListener) {
window.addEventListener('load', function () {
var canvas, context, canvaso, contexto;
// The active tool instance.
var tool;
var tool_default = 'line';
function init() {
// Find the canvas element.
canvaso = document.getElementById('my_canvas_1');
if (!canvaso) {
alert('Error: I cannot find the canvas element!');
return;
}
if (!canvaso.getContext) {
alert('Error: no canvas.getContext!');
return;
}
// Get the 2D canvas context.
contexto = canvaso.getContext('2d');
if (!contexto) {
alert('Error: failed to getContext!');
return;
}
// Add the temporary canvas.
var container = canvaso.parentNode;
canvas = document.createElement('canvas');
if (!canvas) {
alert('Error: I cannot create a new canvas element!');
return;
}
canvas.id = 'imageTemp';
canvas.width = canvaso.width;
canvas.height = canvaso.height;
container.appendChild(canvas);
context = canvas.getContext('2d');
// Get the tool select input.
var tool_select = document.getElementById('dtool');
if (!tool_select) {
alert('Error: failed to get the dtool element!');
return;
}
tool_select.addEventListener('change', ev_tool_change, false);
// Activate the default tool.
if (tools[tool_default]) {
tool = new tools[tool_default]();
tool_select.value = tool_default;
}
// Attach the mousedown, mousemove and mouseup event listeners.
canvas.addEventListener('mousedown', ev_canvas, false);
canvas.addEventListener('mousemove', ev_canvas, false);
canvas.addEventListener('mouseup', ev_canvas, false);
}
// The general-purpose event handler. This function just determines the mouse
// position relative to the canvas element.
function ev_canvas(ev) {
if (ev.layerX || ev.layerX == 0) { // Firefox
ev._x = ev.layerX;
ev._y = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) { // Opera
ev._x = ev.offsetX;
ev._y = ev.offsetY;
}
// Call the event handler of the tool.
var func = tool[ev.type];
if (func) {
func(ev);
}
}
// The event handler for any changes made to the tool selector.
function ev_tool_change(ev) {
if (tools[this.value]) {
tool = new tools[this.value]();
}
}
// This function draws the #imageTemp canvas on top of #my_cavas_1, after which
// #imageTemp is cleared. This function is called each time when the user
// completes a drawing operation.
function img_update() {
contexto.drawImage(canvas, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);
}
// This object holds the implementation of each drawing tool.
var tools = {};
// The drawing pencil.
tools.pencil = function () {
var tool = this;
this.started = false;
// This is called when you start holding down the mouse button.
// This starts the pencil drawing.
this.mousedown = function (ev) {
context.beginPath();
context.moveTo(ev._x, ev._y);
tool.started = true;
};
// This function is called every time you move the mouse. Obviously, it only
// draws if the tool.started state is set to true (when you are holding down
// the mouse button).
this.mousemove = function (ev) {
if (tool.started) {
context.lineTo(ev._x, ev._y);
context.stroke();
}
};
// This is called when you release the mouse button.
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
img_update();
}
};
};
// The rectangle tool.
tools.rect = function () {
var tool = this;
this.started = false;
this.mousedown = function (ev) {
tool.started = true;
tool.x0 = ev._x;
tool.y0 = ev._y;
};
this.mousemove = function (ev) {
if (!tool.started) {
return;
}
var x = Math.min(ev._x, tool.x0),
y = Math.min(ev._y, tool.y0),
w = Math.abs(ev._x - tool.x0),
h = Math.abs(ev._y - tool.y0);
context.clearRect(0, 0, canvas.width, canvas.height);
if (!w || !h) {
return;
}
context.strokeRect(x, y, w, h);
};
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
img_update();
}
};
};
// The line tool.
tools.line = function () {
var tool = this;
this.started = false;
this.mousedown = function (ev) {
tool.started = true;
tool.x0 = ev._x;
tool.y0 = ev._y;
};
this.mousemove = function (ev) {
if (!tool.started) {
return;
}
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(tool.x0, tool.y0);
context.lineTo(ev._x, ev._y);
context.stroke();
context.closePath();
};
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
img_update();
}
};
};
init();
}, false);
}
This is my HTML CANVAS TAG
<canvas id="my_canvas_1" width="300" height="300" onclick="CLIPBOARD_CLASS('my_canvas_1',true);"></canvas>
I am trying to implement custom draggable directive in angularjs but it trows
Range error . what is wrong in this code
(function (window, angular, undefined) {
var app = angular.module('ngDraggableModule', []);
app.directive('easyDrag', ['$document', function ($document) {
return {
restrict: 'EA',
scope: {
params: '=',
elemId: '='
},
link: function (scope, elem, attrs) {
var isMouseDown = false,
startDrag = false,
position = {},
x = 0,
y = 0,
startX = 0,
startY = 0,
changedPos = 0;
elem.bind('mousedown', onMouseDown);
function onMouseDown(e) {
if (angular.isDefined(scope.params.disabled) && scope.params.disabled === true) {
return false;
}
isMouseDown = true;
startX = e.screenX - x;
startY = e.screenY - y;
$document.bind('mousemove', onMouseMove);
$document.bind('mouseup', onMouseUp);
}
function onMouseMove(e) {
if (isMouseDown) {
if (!startDrag) {
startDrag = true;
if (angular.isFunction(scope.params.start)) {
scope.params.start(changedPos, e, scope.elemId);
}
}
y = e.screenY - startY;
x = e.screenX - startX;
position = {};
if (angular.isDefined(scope.params.axis)) {
if (scope.params.axis.toLowerCase() == 'x') {
position.marginLeft = x + 'px';
}
else if (scope.params.axis.toLowerCase() == 'y') {
position.marginTop = y + 'px';
}
} else {
position.marginTop = y + 'px';
position.marginLeft = x + 'px';
}
changedPos = position;
elem.css(position);
if (angular.isFunction(scope.params.drag)) {
scope.params.drag(e, changedPos, scope.elemId);
}
}
}
function onMouseUp(e) {
if (!isMouseDown) {
return false;
}
isMouseDown = false;
startDrag = false;
if (angular.isFunction(scope.params.stop)) {
scope.params.stop(changedPos, e, scope.elemId);
}
}
}
}
}]);
})(window, window.angular, undefined);
var app = angular.module('DemoApp',['ngDraggableModule']);
app.controller('MainCtrl',['$scope',function($scope){
$scope.assetDragParams = {
drag : function(e,pos,id){
console.log(id); // here is the error
}
}
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="MainCtrl">
<div easy-drag params="assetDragParams" elem-id="col._id">
drag it
</div>
</div>
calling directive such this trows RangeError : Maximum call stack size exceeded
what is wrong ? thanks in advance.
You need to bind the mousemove + mouseup outside of mousedown, anyway you set isMouseDown = true in the onMouseDown function. All the function binding should be like this:
elem.bind('mousedown', onMouseDown);
$document.bind('mousemove', onMouseMove);
$document.bind('mouseup', onMouseUp);
And onMouseDown function should be:
function onMouseDown(e) {
if (angular.isDefined(scope.params.disabled) && scope.params.disabled === true) {
return false;
}
isMouseDown = true;
startX = e.screenX - x;
startY = e.screenY - y;
}