I'm trying to draw a circle wherever the user clicks on the screen using angular on canvas. My code doesn't seem to be working.
Here's my plnk
http://plnkr.co/edit/rYVLgB14IutNh1F4MN6T?p=preview
var app = angular.module('plunker', []);
app.controller('MainController', function($scope) {
//alert("test");
$scope.doClick = function(event){
var x = event.clientX;
var y = event.clientY;
var offsetX = event.offsetX;
var offsetY = event.offsetY;
//alert(x, y, offsetX, offsetY);
//console.log(x, y, offsetX, offsetY);
var ctx = getContext("2d");
//draw a circle
ctx.beginPath();
ctx.arc(x, y, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
};
$scope.test="test";
});
Any help appreciated.
So the problem here is not using canvas correctly.
You need to add an ID, Class or target all canvas elements, In this case I added an ID to your canvas element this way I can target it with document.getElementById
<canvas id="canvas" ng-click="doClick($event)" width="600" height= "600"></canvas>
And in your javascript you weren't targeting the canvas element and applying the context to it.
So this is what your new doubleCLick function will look like:
$scope.doClick = function(event){
var x = event.clientX;
var y = event.clientY;
var offsetX = event.offsetX;
var offsetY = event.offsetY;
alert(x, y, offsetX, offsetY);
/// These are the 2 new lines, see you target the canvas element then apply it to getContext
var canvasElement = document.getElementById("canvas");
var ctx = canvasElement.getContext("2d");
//draw a circle
ctx.beginPath();
ctx.arc(x, y, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
};
I still recommend putting this code in a service.
Related
I don't know js, I write on python, but I need to draw circles on web page at the clicked location. So, for really I use selenium and I need to see where the click is. Because I don't click the dom elements, I click coordinates and sometimes Selenium click wrong, so I want to control it.
I tried some code like below, of course it doesn't work, i don't know why. So I found the similar solution. It doesn't work for me. So I can't find the working solution for highlighting the clicks.
var canv = document.createElement('canvas');
canv.id = 'canvas';
document.body.appendChild(canv);
document.getElementById('canvas').appendChild(canv);
onclick = function showCoords(event) {
var x = event.clientX;
var y = event.clientY;
var radius = 5;
var canvas = document.getElementsByTagName('canvas');
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(x, y, radius, 40, 0, 2 * Math.PI);
ctx.stroke();
var coords = 'X coords: ' + x + ', Y coords: ' + y;
console.log(coords);
}
You try to append the canvas to the canvas
This works
var canv = document.createElement('canvas');
canv.id = 'canvas';
document.body.appendChild(canv);
var ctx = canv.getContext('2d');
canv.addEventListener("click",function(event) {
var x = event.clientX;
var y = event.clientY;
var radius = 5;
ctx.beginPath();
ctx.arc(x, y, radius, 40, 0, 2 * Math.PI);
ctx.stroke();
var coords = 'X coords: ' + x + ', Y coords: ' + y;
console.log(coords);
})
The decision is
var myCanvas = document.createElement('canvas');
document.body.appendChild(myCanvas);
myCanvas.id = 'canvas';
myCanvas.style.position = 'absolute';
myCanvas.style.left = "0px";
myCanvas.style.top = "0px";
myCanvas.width = window.innerWidth;
myCanvas.height = window.innerHeight;
var ctx = myCanvas.getContext('2d');
myCanvas.addEventListener("click", function (event) {
var x = event.clientX;
var y = event.clientY;
ctx.fillStyle = "#2980b9";
ctx.beginPath();
ctx.arc(x, y, 10, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath();
setTimeout(function () { ctx.clearRect(0, 0, myCanvas.width, myCanvas.height) }, 300);
})
I have an application where I need to move the points I created to a certain part of the canvas. How can I do it?
$("#canvas").click(function(e){
getPosition(e);
});
var pointSize = 1;
function getPosition(event){
var rect = canvas.getBoundingClientRect();
var x = event.clientX - rect.left;
var y = event.clientY - rect.top;
console.log(x,y)
drawCoordinates(x,y);
}
function drawCoordinates(x,y){
var ctx = document.getElementById("canvas").getContext("2d");
ctx.fillStyle = "#ff2626"; // Red color
ctx.beginPath();
ctx.arc(x, y, pointSize, 0, Math.PI * 2, true);
ctx.fill();
}
http://jsfiddle.net/bfe8160h/
There's no easy way to drag drawn things on canvas, so you're gonna have to store all points' positions, and redraw the whole canvas.
Something like this:
var points = []
var drag_point = -1
$("#canvas").mousedown(function(e){
var pos = getPosition(e)
drag_point = getPointAt(pos.x,pos.y)
if(drag_point==-1){ // no point at this position, add new point
drawCoordinates(pos.x,pos.y)
points.push(pos)
}
});
$("#canvas").mousemove(function(e){
if(drag_point!=-1){ // if currently dragging a point...
var pos = getPosition(e)
//...update points position...
points[drag_point].x = pos.x
points[drag_point].y = pos.y
redraw() // ... and redraw canvas
}
});
$("#canvas").mouseup(function(e){
drag_point = -1
});
function getPointAt(x,y){
for(var i=0;i<points.length;i++){
if(Math.abs(points[i].x-x)<pointSize && Math.abs(points[i].y-y)<pointSize) // check if x,y is inside points bounding box. replace with pythagoras theorem if you like.
return i
}
return -1 // no point at x,y
}
function redraw(){
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height); // clear canvas
for(var i=0;i<points.length;i++){ // draw all points again
drawCoordinates(points[i].x,points[i].y)
}
}
function getPosition(event){
var rect = canvas.getBoundingClientRect();
var x = event.clientX - rect.left;
var y = event.clientY - rect.top;
return {x:x,y:y}
}
function drawCoordinates(x,y){
var ctx = document.getElementById("canvas").getContext("2d");
ctx.fillStyle = "#ff2626"; // Red color
ctx.beginPath();
ctx.arc(x, y, pointSize, 0, Math.PI * 2, true);
ctx.fill();
}
import
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
and use jquery to drag your div..Example:
$('#divname').draggable();
When I add
ctx.addEventListener('mousedown', onDown, false);
The canvas drawing (background and shapes) disappear and the page is blank, and then when I remove this event listener from the code they reappear again. Just wondering why this is happening? Thanks in advance
<script>
var ctx, W, H;
var x = 10;
window.onload = function() {
var canvas = document.getElementById("canvas");
W = window.innerWidth;
H = window.innerHeight;
canvas.width = W;
canvas.height = H;
ctx = canvas.getContext("2d");
ctx.addEventListener('mousedown', onDown, false); //When this is here, canvas drawing disappears, when it's not here canvas drawing reappears again
setInterval(draw, 1);
function draw() {
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "#E6E6FF";
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = "black";
ctx.fillRect(x,20,10,10);
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,80);
ctx.fill();
}
}
function onDown(event) {
//where x is found
cx = event.pageX
cy = event.pageY
alert("X,Y ="+cx+','+cy);
}
You can't add an event listener to the canvas's context. You'll need to add it to the canvas itself.
Instead of:
ctx.addEventListener('mousedown', onDown, false);
… do this:
canvas.addEventListener('mousedown', onDown, false);
jsBin demo
use:
ctx.canvas.addEventListener
or:
canvas.addEventListener
cause context is just an Object in which the HTMLElementCanvas lives in.
To spot such errors your-self, the easiest way is to debug your code using Developer Tools, opening the console tab and reading the errors you're shown:
Seemed simple enough to draw circles and text in an HTML5 canvas, but I get non-intuitive behavior. The circles get drawn nice and pretty, then the more circles I draw, the older circles become more and more octagonal shaped. Very strange to me... Also, the text disappears from the old circles and only appears on the last circle drawn. What's the proper way to do this with canvases?
$("#circles_container").on("click", "#circles_canvas", function(event) {
var canvas = document.getElementById('circles_canvas');
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
var w = 16;
var x = event.pageX;
var y = Math.floor(event.pageY-$(this).offset().top);
ctx.fillStyle = "rgb(200,0,0)";
ctx.arc(x, y, w/2, 0, 2 * Math.PI, false);
ctx.fill();
ctx = canvas.getContext("2d");
ctx.font = '8pt Calibri';
ctx.fillStyle = 'white';
ctx.textAlign = 'center';
ctx.fillText('0', x, y+3);
}
});
Just add this near the start of your function :
ctx.beginPath();
You were drawing a path always longer.
Demo in Stack Snippets & JS Fiddle (click on the canvas)
var canvas = document.getElementById('circles_canvas');
canvas.addEventListener("click", function(event) {
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
var w = 16;
var x = Math.floor(event.pageX-this.offsetLeft);
var y = Math.floor(event.pageY-this.offsetTop);
ctx.beginPath();
ctx.fillStyle = "rgb(200,0,0)";
ctx.arc(x, y, w/2, 0, 2 * Math.PI, false);
ctx.fill();
ctx.font = '8pt Calibri';
ctx.fillStyle = 'white';
ctx.textAlign = 'center';
ctx.fillText('0', x, y+3);
}
})
canvas {
border: 1px solid black;
}
<h1>Click Canvas Below</h1>
<canvas id="circles_canvas"></canvas>
I am trying to draw a circle using mouse on the canvas using mouse events, but it does not draw anything:
tools.circle = function () {
var tool = this;
this.started = false;
this.mousedown = function (ev) {
tool.started = true;
tool.x0 = ev._x;
tool.y0 = ev._y;
ctx.moveTo(tool.x0,tool.y0);
};
this.mousemove = function (ev) {
var centerX = Math.max(tool.x0,ev._x) - Math.abs(tool.x0 - ev._x)/2;
var centerY = Math.max(tool.y0,ev._y) - Math.abs(tool.y0 - ev._y)/2;
var distance = Math.sqrt(Math.pow(tool.x0 - ev._x,2) + Math.pow(tool.y0 - ev._y));
context.circle(tool.x0, tool.y0, distance/2,0,Math.PI*2 ,true);
context.stroke();
};
};
What am I doing wrong?
Well, this code snippet doesn't tell us much, but there are a couple of obvious errors in your code.
First, DOM Event object doesn't have _x and _y properties. but rather clientX and clientY or pageX and pageY.
To get relative mouse coordinates from the current event object, you would do something like:
element.onclick = function(e) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
}
Next, canvas' 2d context doesn't have a method called circle, but you could write your own, maybe something like:
var ctx = canvas.context;
ctx.fillCircle = function(x, y, radius, fillColor) {
this.fillStyle = fillColor;
this.beginPath();
this.moveTo(x, y);
this.arc(x, y, radius, 0, Math.PI*2, false);
this.fill();
}
Anyhow, here's a test html page to test this out: http://jsfiddle.net/ArtBIT/kneDX/
I hope this helps.
Cheers