Place image on canvas at same x,y position as mouse onclick - javascript

I'm trying to make a web app that lets the user insert small images of characters on an html canvas. The plan is to have the user click a button on a virtual keyboard, and then click on the canvas to have the corresponding character appear wherever the user clicked. Right now I'm just trying to get one image to appear on the canvas when clicked, but so far it isn't doing anything. Here's the code I have now, which is embedded in the html file.
<script type="text/javascript">
var mathCanvas = document.getElementById("matharea");
var ctx = mathCanvas.getContext("2d");
var el = mathCanvas;
var xPos = 0;
var yPos = 0;
while(el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)){
xPos += el.offsetLeft - el.scrollLeft;
yPos += el.offsetTop - el.scrollTop;
el = el.parentNode;
}
var img = new Image();
img.src = "five.png";
mathCanvas.onclick = function(event){
var x = event.clientX - xPos;
var y = event.clientY - yPos;
ctx.drawImage(img,x,y);
};
</script>
I've tested the onclick event, and it returns coords, but the image won't appear. What's going wrong here?

This should work since the click event will be firing on the canvas itself:
var mathCanvas = document.getElementById("matharea");
var ctx = mathCanvas.getContext("2d");
var img = new Image();
img.src = "five.png";
mathCanvas.onclick = function(event){
var x = event.offsetX;
var y = event.offsetY;
ctx.drawImage(img,x,y);
};
To center the image on the point:
var mathCanvas = document.getElementById("matharea");
var ctx = mathCanvas.getContext("2d");
var img = new Image();
img.src = "five.png";
mathCanvas.onclick = function(event){
var x = Math.round(event.offsetX - img.width/2);
var y = Math.round(event.offsetY - img.height/2);
ctx.drawImage(img,x,y);
};

Related

HTML5 Canvas - Drag and Drop co-ordinates on rescale

//VARIABLES
//Drag Object Size
dragRadius = 100;
//Destination Size
destHeight = 434;
destWidth = 220;
var RosieDrag = new lib.RosieDrag();
//Drag Object Creation
//Placed inside a container to hold both label and shape
var test = new lib.test();
stage.addChild(test);
test.x = 525;
test.y = 1035;
var dragger = new createjs.Container();
dragger.x = 250;
dragger.y = 460;
dragger.addChild(RosieDrag);
dragger.setBounds(100, 100, dragRadius*2, dragRadius*2);
//DragRadius * 2 because 2*r = width of the bounding box
var RosieDrop = new lib.RosieDrop();
var destination = new createjs.Container();
destination.x = 900;
destination.y = 240;
destination.setBounds(950, 350, 100, 100);
destination.addChild(RosieDrop);
//DRAG FUNCTIONALITY =====================
dragger.on("pressmove", function(evt){
evt.currentTarget.x = evt.stageX;
evt.currentTarget.y = evt.stageY;
stage.update(); //much smoother because it refreshes the screen every pixel movement instead of the FPS set on the Ticker
if(intersect(evt.currentTarget, destination)){
evt.currentTarget.alpha=0.2;
}else{
evt.currentTarget.alpha=1;
}
});
//Mouse UP and SNAP====================
dragger.on("pressup", function(evt) {
if(intersect(evt.currentTarget, destination)){
test.gotoAndPlay(5);
dragger.x = destination.x + destWidth/2;
dragger.y = destination.y + destHeight/2;
dragger.alpha = 1;
stage.update(evt);
}
});
//Tests if two objects are intersecting
//Sees if obj1 passes through the first and last line of its
//bounding box in the x and y sectors
//Utilizes globalToLocal to get the x and y of obj1 in relation
//to obj2
//PRE: Must have bounds set for each object
//Post: Returns true or false
function intersect(obj1, obj2){
var objBounds1 = obj1.getBounds().clone();
var objBounds2 = obj2.getBounds().clone();
var pt = obj1.globalToLocal(objBounds2.x, objBounds2.y);
var h1 = -(objBounds1.height / 2 + objBounds2.height);
var h2 = objBounds2.width / 2;
var w1 = -(objBounds1.width / 2 + objBounds2.width);
var w2 = objBounds2.width / 2;
if(pt.x > w2 || pt.x < w1) return false;
if(pt.y > h2 || pt.y < h1) return false;
return true;
}
//Adds the object into stage
stage.addChild(destination, dragger);
stage.mouseMoveOutside = true;
stage.update();
Hi,
I've made a simple drag and drop in a canvas. It works fine but when the canvas resizes to the window it changes the position of the object when it is picked up and also of the drop area (Interestingly it still draws things in the right position and places the object in the right position after it is dropped.
I'm sure I'm missing something simple, here's my code:

How to draw rectangles on SVG on click event?

I am using raphael js in my application. Here I need to draw a small rectangle on a point of clicking in raphael paper. I need to connect these rectangle using a line. Can anyone make DEMO of this. I am adding sample DEMO. Please update this.
My DEMO.:
HERE
var paper = Raphael("editor", 635,500),
canvas= document.getElementById('editor').style.backgroundColor='gray';
Now I need to draw samll rectangles on clicking raphael paper and joing them with a line.
This should do the trick; http://jsfiddle.net/9dsgcv1c/1/
var paper = Raphael("editor", 635,500),
canvas= document.getElementById('editor').style.backgroundColor='gray';
var offsetx = paper.canvas.offsetLeft;
var offsety = paper.canvas.offsetTop;
var prevRect = null;
var rWidth = 50;
paper.canvas.onmousedown = function(e) {
var posX = e.pageX-offsetx;
var posY = e.pageY-offsety;
var rectX = posX - (rWidth/2)
var rectY = posY - (rWidth/2)
var c = paper.rect(rectX, rectY, rWidth, rWidth).attr({fill:"#fff"});
if(prevRect) {
var p = "M"+prevRect.x +" " +prevRect.y +"L"+posX+" "+posY
var line = paper.path(p);
}
prevRect = {x: posX, y:posY};
}
-
<b>Click on CAMVAS to draw rectangle</b>
<div id="editor"></div>

DIV rotate in Javascript

I am currently trying to rotate this div toward the mouse pointer, and it hasnt worked. I even tried going to a chat room about it. Currently, It sorta rotates toward the mouse...here is my code so far:
var x = 0;
var y = 0;
document.addEventListener("mousemove", function(event){
x = Number(event.pageX);
y = Number(event.pageY);
}, false);
setInterval(function(){
var boxX = document.getElementById('temp').style.left;
boxX = Number(boxX.substring(0, boxX.length - 1));
var boxX = screen.width * ((boxX)/100);
var boxY = document.getElementById('temp').style.top;
boxY = Number(boxY.substring(0, boxY.length - 1));
var boxY = screen.width * ((boxY)/100);
var slope = [Math.round(x - boxX),Math.round(y - boxY)];
//x,y
var angle = Math.round(Math.atan(slope[1]/slope[0]) *100) ;
document.getElementById('temp').style.transform = "translate(-50%,-50%) rotate(0deg)";
document.getElementById('temp').style.transform = "translate(-50%,-50%) rotate("+angle+"deg)";
}, 500);

Clickable images in a canvas

I am trying to make the images inside a canvas clickable, but I am confused on how to go about that, here is what I have currently, I just want pictures[0] to be clickable and that alert to occur once it is clicked, but for some reason it is not working. How can i make it so that when picture[0] is clicked the alert goes off.
var images = document.getElementsByTagName("img");
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var left = c.offsetLeft;
var top = c.offsetTop;
var pictures = [];
//wheel
pictures[0] = new Image();
pictures[0].src = 'images/Layer8.png';
//bg
pictures[1] = new Image();
pictures[1].src = 'images/Layer0.png';
//gear
pictures[2] = new Image();
pictures[2].src = 'images/Layer7.png';
//speed
pictures[3] = new Image();
pictures[3].src = 'images/Layer14.png';
//dial1
pictures[4] = new Image();
pictures[4].src = 'images/Layer18.png';
//dial2
pictures[5] = new Image();
pictures[5].src = 'images/Layer16.png';
//dial3
pictures[6] = new Image();
pictures[6].src = 'images/Layer17.png';
c.addEventListener('click', function(event){
var x = event.pageX - left,
y = event.pageY - top;
pictures.forEach(function(fx,fy,fwidth,fheight,x,y) {
if (y > fy && y < fy + fheight
&& x > fx && x < fx + fwidth) {
alert('clicked an element');
}
});
}, false);
function load(){
ctx.drawImage(pictures[1],0,0);
ctx.drawImage(pictures[2],468,263);
ctx.drawImage(pictures[3],89,77);
ctx.drawImage(pictures[4],146,153);
ctx.drawImage(pictures[5],278,153);
ctx.drawImage(pictures[6],206,119);
ctx.drawImage(pictures[0],fx,fy,fwidth,fheight);
}
var fx = 84;
var fy = 60;
var fwidth = 283;
var fheight = 276;
window.onload = load;
Ok I understand what you are trying to do. Unfortunately, images in the canvas are not DOM elements, only the canvas itself is one. This means using jQuery you can call:
$('#myCanvas').on('click', function() {});
or natively:
c.addEventListener('click', function(){});
However, the fabricjs.com library may prove to be useful to you in this case.

replacing cursor with image to be used as target in javascript

I've tried for a couple of weeks to trouble shoot this problem and I've come to a dead end.
as a word of warning I'm very new to coding and I may not be able to understand much.
I'm trying to draw an image at the location of the mouse.
this is my script so far
$(function()
{
var canvas = $('#canvas')[0];
var context = canvas.getContext("2d");
var img = new Image();
img.src = 'cross.png';
function getTopLeft(elm)
{
var x, y = 0;
x = elm.offsetLeft;
y = elm.offsetTop;
elm = elm.offsetParent;
while(elm != null)
{
x = parseInt(x) + parseInt(elm.offsetLeft);
y = parseInt(y) + parseInt(elm.offsetTop);
elm = elm.offsetParent;
}
return {Top:y, Left: x};
}
canvas.style.cursor = "none";
canvas.addEventListener("mousemove", function (ev)
{
var mouseX = ev.pageX - getTopLeft(canvas).Left;
var mouseY = ev.pageX - getTopLeft(canvas).Top;
});
function animate()
{
context.onmousemove = function(evt)
{
context.clearRect(0,0,canvas.width,canvas.height);
context.drawImage(img, Left, Top);
}
}
});
I think the problem lies in defining the x y value of the picture ive tried every variable used in the code but to no avail the script loads without error but doesnt draw the image at the mouse location.
I have just realised also that i need the image to be centred over the mouse position.

Categories

Resources