Paint Basic Line in Canvas [closed] - javascript

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

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

Unexpected result with range input values

This problem is (probably) not caused by the width/height being in the CSS, because it isn't. (How to avoid HTML Canvas auto-stretching)
When trying to make rage inputs to demonstrate an issue I was having, I found that when using range inputs it acted stranger. It seems to be representing a larger number than what I'm passing in.
Please check my code out and tell me what's causing all this. http://codepen.io/Magnesium/pen/wMwwgx
var engine = function(canvas) { // Trying to make a game engine when the problems started
this.canvas = canvas.getContext("2d");
this.defaultColor = "#FF0000";
this.clearCanvas = function() { // Clears canvas
this.canvas.clearRect(0, 0, canvas.width, canvas.height);
};
this.square = function(x, y, size, color) { // Makes a square. I don't see any problems, but if the error is caused by me it would probably be here
if (color == undefined) color = this.defaultColor;
this.canvas.fillStyle = color;
this.canvas.fillRect(x, y, x + size, y + size);
};
}
var canvas = document.getElementById("canvas");
var rangeX = document.getElementById("x");
var rangeY = document.getElementById("y");
var size = document.getElementById("sz");
var outX = document.getElementById("ox");
var outY = document.getElementById("oy");
var outSize = document.getElementById("osz");
var out = document.getElementById("out");
var enjin = new engine(canvas); // New engine
var defalt = false;
var src = document.getElementById("src");
setInterval(function() { // Called ~30 times a second
enjin.clearCanvas();
defalt ? enjin.square(50, 50, 50) : enjin.square(rangeX.value, rangeY.value, size.value);
defalt ? out.innerHTML = "enjin.square(50, 50, 50);" : out.innerHTML = "enjin.square("+rangeX.value+", "+rangeY.value+", "+size.value+");";
defalt ? src.innerHTML = "Using in-code values" : src.innerHTML = "Using slider values";
outX.innerHTML = rangeX.value;
outY.innerHTML = rangeY.value;
outSize.innerHTML = size.value;
}, 30);
The values you're passing to enjin.square are strings. You need to parse them to int:
enjin.square(parseInt(rangeX.value), parseInt(rangeY.value), parseInt(size.value));
Here's a working example:
var engine = function(canvas) { // Trying to make a game engine when the problems started
this.canvas = canvas.getContext("2d");
this.defaultColor = "#FF0000";
this.clearCanvas = function() { // Clears canvas
this.canvas.clearRect(0, 0, canvas.width, canvas.height);
};
this.square = function(x, y, size, color) { // Makes a square. I don't see any problems, but if the error is caused by me it would probably be here
if (color == undefined) color = this.defaultColor;
this.canvas.fillStyle = color;
this.canvas.fillRect(x, y, x + size, y + size);
};
}
var canvas = document.getElementById("canvas");
var rangeX = document.getElementById("x");
var rangeY = document.getElementById("y");
var size = document.getElementById("sz");
var outX = document.getElementById("ox");
var outY = document.getElementById("oy");
var outSize = document.getElementById("osz");
var out = document.getElementById("out");
var enjin = new engine(canvas); // New engine
var defalt = false;
var src = document.getElementById("src");
setInterval(function() { // Called ~30 times a second
enjin.clearCanvas();
defalt ? enjin.square(50, 50, 50) : enjin.square(parseInt(rangeX.value), parseInt(rangeY.value), parseInt(size.value));
defalt ? out.innerHTML = "enjin.square(50, 50, 50);" : out.innerHTML = "enjin.square(" + rangeX.value + ", " + rangeY.value + ", " + size.value + ");";
defalt ? src.innerHTML = "Using in-code values" : src.innerHTML = "Using slider values";
outX.innerHTML = rangeX.value;
outY.innerHTML = rangeY.value;
outSize.innerHTML = size.value;
}, 30);
#canvas {
border: 1px solid black;
}
<canvas id='canvas' width='400' height='400'></canvas>
<br />X
<input type='range' id='x' /><span id='ox'></span>
<br />Y
<input type='range' id='y' /><span id='oy'></span>
<br />Size
<input type='range' id='sz' /><span id='osz'></span>
<br /><span id='out'></span>
<br />
<button onclick='defalt = !defalt;'>Default value toggle</button>
<span id='src'></span>
And a updated pen.

Creating a click event in Javascript Canvas

I'm having trouble creating a click event for my Javascript canvas game. So far I have been following a tutorial, however the way you interact with the game is through mouse hover. I would like to change it so that instead of hovering over objects in the canvas to interact, I instead use a mouse click.
The following is the code I use to detect the mouse hover.
getDistanceBetweenEntity = function (entity1,entity2) //return distance
{
var vx = entity1.x - entity2.x;
var vy = entity1.y - entity2.y;
return Math.sqrt(vx*vx+vy*vy);
}
testCollisionEntity = function (entity1,entity2) //return if colliding
{
var distance = getDistanceBetweenEntity(entity1,entity2);
return distance < 50;
}
I then use this in a loop to interact with it.
var isColliding = testCollisionEntity(player,nounList[key]);
if(isColliding)
{
delete nounList[key];
player.score = player.score + 10;
}
Below is a complete copy of my game at its current state.
<canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas>
<script>
var ctx = document.getElementById("ctx").getContext("2d");
ctx.font = '30px Arial';
//Setting the height of my canvas
var HEIGHT = 500;
var WIDTH = 500;
//Player class
var player =
{
x:50,
spdX:30,
y:40,
spdY:5,
name:'P',
score:0,
};
//Creating arrays
var nounList ={};
var adjectivesList ={};
var verbsList ={};
getDistanceBetweenEntity = function (entity1,entity2) //return distance
{
var vx = entity1.x - entity2.x;
var vy = entity1.y - entity2.y;
return Math.sqrt(vx*vx+vy*vy);
}
testCollisionEntity = function (entity1,entity2) //return if colliding
{
var distance = getDistanceBetweenEntity(entity1,entity2);
return distance < 50;
}
Nouns = function (id,x,y,name)
{
var noun =
{
x:x,
y:y,
name:name,
id:id,
};
nounList[id] = noun;
}
Adjectives = function (id,x,y,name)
{
var adjective =
{
x:x,
y:y,
name:name,
id:id,
};
adjectivesList[id] = adjective;
}
Verbs = function (id,x,y,name)
{
var verb =
{
x:x,
y:y,
name:name,
id:id,
};
verbsList[id] = verb;
}
document.onmousemove = function(mouse)
{
var mouseX = mouse.clientX;
var mouseY = mouse.clientY;
player.x = mouseX;
player.y = mouseY;
}
updateEntity = function (something)
{
updateEntityPosition(something);
drawEntity(something);
}
updateEntityPosition = function(something)
{
}
drawEntity = function(something)
{
ctx.fillText(something.name,something.x,something.y);
}
update = function ()
{
ctx.clearRect(0,0,WIDTH,HEIGHT);
drawEntity(player);
ctx.fillText("Score: " + player.score,0,30);
for(var key in nounList)
{
updateEntity(nounList[key]);
var isColliding = testCollisionEntity(player,nounList[key]);
if(isColliding)
{
delete nounList[key];
player.score = player.score + 10;
}
}
for(var key in adjectivesList)
{
updateEntity(adjectivesList[key])
var isColliding = testCollisionEntity(player,adjectivesList[key]);
if(isColliding)
{
delete adjectivesList[key];
player.score = player.score - 1;
}
}
for(var key in verbsList)
{
updateEntity(verbsList[key])
var isColliding = testCollisionEntity(player,verbsList[key]);
if(isColliding)
{
delete verbsList[key];
player.score = player.score - 1;
}
}
if(player.score >= 46)
{
ctx.clearRect(0,0,WIDTH,HEIGHT);
ctx.fillText("Congratulations! You win!",50,250);
ctx.fillText("Refresh the page to play again.",50,300);
}
}
Nouns('N1',150,350,'Tea');
Nouns('N2',400,450,'Park');
Nouns('N3',250,150,'Knee');
Nouns('N4',50,450,'Wall');
Nouns('N5',410,50,'Hand');
Adjectives('A1',50,100,'Broken');
Adjectives('A2',410,300,'Noisy');
Verbs('V1',50,250,'Smell');
Verbs('V2',410,200,'Walk');
setInterval(update,40);
To summarize all I want to do is change it so that instead of mousing over words to delete them you have to click.
(Apologies for not using correct terminology in places, my programming knowledge is quite limited.)
You can have your canvas listen for mouse clicks on itself like this:
// get a reference to the canvas element
var canvas=document.getElementById('ctx');
// tell canvas to listen for clicks and call "handleMouseClick"
canvas.onclick=handleMouseClick;
In the click handler, you'll need to know the position of your canvas relative to the viewport. That's because the browser always reports mouse coordinates relative to the viewport. You can get the canvas position relative to the viewport like this:
// get the bounding box of the canvas
var BB=canvas.getBoundingClientRect();
// get the left X position of the canvas relative to the viewport
var BBoffsetX=BB.left;
// get the top Y position of the canvas relative to the viewport
var BBoffsetY=BB.top;
So your mouseClickHandler might look like this:
// this function will be called when the user clicks
// the mouse in the canvas
function handleMouseClick(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// get the canvas postion relative to the viewport
var BB=canvas.getBoundingClientRect();
var BBoffsetX=BB.left;
var BBoffsetY=BB.top;
// calculate the mouse position
var mouseX=e.clientX-BBoffsetX;
var mouseY=e.clientY-BBoffsetY;
// report the mouse position using the h4
$position.innerHTML='Click at '+parseInt(mouseX)+' / '+parseInt(mouseY);
}
If your game doesn't let the window scroll or resize then the canvas postion won't change relative to the viewport. Then, for better performance, you can move the 3 lines relating to getting the canvas position relative to the viewport to the top of your app.
// If the browser window won't be scrolled or resized then
// get the canvas postion relative to the viewport
// once at the top of your app
var BB=canvas.getBoundingClientRect();
var BBoffsetX=BB.left;
var BBoffsetY=BB.top;
function handleMouseClick(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// calculate the mouse position
var mouseX=e.clientX-BBoffsetX;
var mouseY=e.clientY-BBoffsetY;
// report the mouse position using the h4
$position.innerHTML='Click at '+parseInt(mouseX)+' / '+parseInt(mouseY);
}

javascript alert when canvas is clicked

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

Displaying Hidden Div on Canvas position mousemoves

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.

Categories