Extending existing canvas signing script - javascript

I lack javascript / Jquery skills to extend the script like I want. I wanted to use this script to have 3 signfields on a page. All 3 will be signed separately and should be saved later as 3 images to create a PDF via FPDF with. My problem is that 3x "" doesnt provide the hoped for result. Thats why I wanted to ask If some1 could explain to me how to do that.
Greetings.
var isSign = false;
var leftMButtonDown = false;
jQuery(function() {
//Initialize sign pad
init_Sign_Canvas();
});
function fun_submit() {
if (isSign) {
var canvas = $("#canvas").get(0);
var imgData = canvas.toDataURL();
jQuery('#page').find('p').remove();
jQuery('#page').find('img').remove();
jQuery('#page').append(jQuery('<p>Your Sign:</p>'));
jQuery('#page').append($('<img/>').attr('src', imgData));
closePopUp();
} else {
alert('Please sign');
}
}
function closePopUp() {
jQuery('#divPopUpSignContract').popup('close');
jQuery('#divPopUpSignContract').popup('close');
}
function init_Sign_Canvas() {
isSign = false;
leftMButtonDown = false;
//Set Canvas width
var sizedWindowWidth = $(window).width();
if (sizedWindowWidth > 700)
sizedWindowWidth = $(window).width() / 2;
else if (sizedWindowWidth > 350)
sizedWindowWidth = sizedWindowWidth - 100;
else
sizedWindowWidth = sizedWindowWidth - 50;
$("#canvas").width(350);
$("#canvas").height(100);
$("#canvas").css("border", "1px solid #000");
var canvas = $("#canvas").get(0);
canvasContext = canvas.getContext('2d');
if (canvasContext) {
canvasContext.canvas.width = 350;
canvasContext.canvas.height = 100;
canvasContext.fillStyle = "#fff";
canvasContext.fillRect(0, 0, sizedWindowWidth, 350);
canvasContext.moveTo(100, 150);
canvasContext.lineTo(sizedWindowWidth - 50, 150);
canvasContext.stroke();
canvasContext.fillStyle = "#000";
canvasContext.font = "20px Arial";
canvasContext.fillText("x", 40, 155);
}
// Bind Mouse events
$(canvas).on('mousedown', function(e) {
if (e.which === 1) {
leftMButtonDown = true;
canvasContext.fillStyle = "#000";
var x = e.pageX - $(e.target).offset().left;
var y = e.pageY - $(e.target).offset().top;
canvasContext.moveTo(x, y);
}
e.preventDefault();
return false;
});
$(canvas).on('mouseup', function(e) {
if (leftMButtonDown && e.which === 1) {
leftMButtonDown = false;
isSign = true;
}
e.preventDefault();
return false;
});
// draw a line from the last point to this one
$(canvas).on('mousemove', function(e) {
if (leftMButtonDown == true) {
canvasContext.fillStyle = "#000";
var x = e.pageX - $(e.target).offset().left;
var y = e.pageY - $(e.target).offset().top;
canvasContext.lineTo(x, y);
canvasContext.stroke();
}
e.preventDefault();
return false;
});
//bind touch events
$(canvas).on('touchstart', function(e) {
leftMButtonDown = true;
canvasContext.fillStyle = "#000";
var t = e.originalEvent.touches[0];
var x = t.pageX - $(e.target).offset().left;
var y = t.pageY - $(e.target).offset().top;
canvasContext.moveTo(x, y);
e.preventDefault();
return false;
});
$(canvas).on('touchmove', function(e) {
canvasContext.fillStyle = "#000";
var t = e.originalEvent.touches[0];
var x = t.pageX - $(e.target).offset().left;
var y = t.pageY - $(e.target).offset().top;
canvasContext.lineTo(x, y);
canvasContext.stroke();
e.preventDefault();
return false;
});
$(canvas).on('touchend', function(e) {
if (leftMButtonDown) {
leftMButtonDown = false;
isSign = true;
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<canvas id="canvas">Canvas is not supported</canvas>
<canvas id="canvas">Canvas is not supported</canvas>
<canvas id="canvas">Canvas is not supported</canvas>

Related

Get image data from canvas

I'm trying to add a signature feature to a web app. Users should have the possibility to sign with a pencil on a touch screen device. I'm using HTML5 canvas, JavaScript and PHP to get things done. I found a script for both mouse and touch support.
The drawing on the canvas works fine. When I submit the form, the scribble will get cropped properly (so it seems). But the generated base64-png data (saved in a database) is an empty image.
Here's the JS code I'm using:
var canvas, ctx;
var mouseX, mouseY, mouseDown = 0;
var touchX, touchY;
var lastX, lastY = -1;
canvas = document.getElementById('scribble-canvas');
ctx = canvas.getContext('2d');
canvas.addEventListener('mousedown', scribbleMouseDown, false);
canvas.addEventListener('mousemove', scribbleMouseMove, false);
canvas.addEventListener('mouseup', scribbleMouseUp, false);
canvas.addEventListener('touchstart', scribbleTouchStart, false);
canvas.addEventListener('touchend', scribbleTouchEnd, false);
canvas.addEventListener('touchmove', scribbleTouchMove, false);
function drawLine(ctx, x, y, size) {
if (lastX == -1) {
lastX = x;
lastY = y;
}
ctx.strokeStyle = "#000000";
ctx.lineCap = "round";
ctx.lineWidth = size;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.stroke();
ctx.closePath();
lastX = x;
lastY = y;
}
function scribbleMouseDown() {
mouseDown = 1;
drawLine(ctx, mouseX, mouseY, 3);
}
function scribbleMouseUp() {
mouseDown = 0;
lastX = -1;
lastY = -1;
}
function scribbleMouseMove(e) {
getMousePos(e);
if (mouseDown == 1) {
drawLine(ctx, mouseX, mouseY, 3);
}
}
function getMousePos(e) {
if ( ! e) {
var e = event;
}
if (e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else if (e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
}
function scribbleTouchStart() {
getTouchPos();
drawLine(ctx, touchX, touchY, 3);
event.preventDefault();
}
function scribbleTouchEnd() {
lastX = -1;
lastY = -1;
}
function scribbleTouchMove(e) {
getTouchPos(e);
drawLine(ctx, touchX, touchY, 3);
event.preventDefault();
}
function getTouchPos(e) {
if ( ! e) {
var e = event;
}
if (e.touches) {
if (e.touches.length == 1) {
var touch = e.touches[0];
touchX = touch.pageX - touch.target.offsetLeft;
touchY = touch.pageY - touch.target.offsetTop;
}
}
}
function crop(canvas) {
var w = canvas.width, h = canvas.height;
var pix = {x:[], y:[]};
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var x, y, index;
for (y = 0; y < h; y++) {
for (x = 0; x < w; x++) {
index = (y * w + x) * 4;
if (imageData.data[index+3] > 0) {
pix.x.push(x);
pix.y.push(y);
}
}
}
pix.x.sort(function(a,b){return a-b});
pix.y.sort(function(a,b){return a-b});
var n = pix.x.length-1;
w = 1 + pix.x[n] - pix.x[0];
h = 1 + pix.y[n] - pix.y[0];
var cut = ctx.getImageData(pix.x[0], pix.y[0], w, h);
document.body.style.opacity = 0;
canvas.width = w;
canvas.height = h;
ctx.putImageData(cut, 0, 0);
return canvas.toDataURL();
}
On the PHP side I just pick the data returned by the crop() function and save it to the database.
What I tried so far is to strip off the touch support to see if it works just on mouse devices.
Additional code as suggested by user traktor:
The following jQuery code submits the form with the image data to the PHP script:
$(document).on('click', '#scribble-submit', function(e) {
e.preventDefault();
var btn = $(this);
var data = crop(document.querySelector('#scribble-canvas'));
$.post('/scribble/ax/ins_scribble', $('#form-scribble').serialize() + '&data=' + data, function(ans) {
window.location.href = '/' + btn.data('redirect');
});
});
The PHP part looks like this (using the CI3 framework):
$post = $this->input->post();
$this->db->where('id', $id);
$this->db->update('personen', ['signatur' => $post['data']]);
echo TRUE;
So far, jQuery and PHP works fine. The data is successfully inserted into the database. The LONGBLOB field contains this code:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMQAAAC3CAYAAABNEPEEAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAxKADAAQAAAABAAAAtwAAAAB1wSLaAAAYVElEQVR4Ae2dCZQeVZXHmyUhIYQ1gBAgHSDsCAxbWNPsO4ZBBBkwERxQcEARUUdQdJyj6DjA0VE2YdhBhs2ASAhDwo4gy4GwBmggILIZgbAKM79/893O7er1W r7arn3nH /W reu/ef71Xb63qhdpCssbAMhg0CowBoyuh4iaDYeAeUI0szcnt4P9AJ/gbGEiGer6dN5/EZoG7wGvgzyC3slBuLe9tuArRSGAFSjdsCWA3bmv0RcFsMFih4JRuWQVNUIGaC14E1YpsWA8sAp4DSmtxsGQlXKoSynbFy 48yrsY/VfwPHgDqLKsAN4G/wVuAJmWVlUIFYC9we5AN78TJAvpROJUcPp7IlpBVwFSQV8ebABCssvAFzDtwuya19aWZoVYGceXBWPBumAXoEKsp8Z4sBoYDkL6Z AFfnoJPANWAu B/h4Q/NSn2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Qrh5WCsRQwSvs3vmtNXRVEhHAPeB3oLr69CqXRXAZoO1bWqTCuApcDKQDNE/T35 amH/Iij88GcHrFx0DQGylAhROYOQPPyS4M3gQrwSkCFvRXydzLVgPn2SqgK CCQbSEtZKAsFaIvilUp1J05HuhJLi70HnEaMp9E9dRXq6MB/oUgvgwCCVmTMleI5L1Qt2Y0sO7Oiujq73eAYWCwLpOe hqsa5pXT3oV/rcqoSrEeyAk4wz8P tCAtne45WMAAAAAElFTkSuQmCC
Using this data as an image source for the img tag results in the empty image.
The problem is this jQuery line:
$.post('/scribble/ax/ins_scribble', $('#form-scribble').serialize() + '&data=' + data, function(ans) {
Combining the serialize function and an addition of &data= didn't work. So I changed it to:
$.post('/scribble/ax/ins_scribble', { data: data }, function(ans) {
You code runs fine:
var canvas, ctx;
var mouseX, mouseY, mouseDown = 0;
var touchX, touchY;
var lastX, lastY = -1;
canvas = document.getElementById('scribble-canvas');
ctx = canvas.getContext('2d');
canvas.addEventListener('mousedown', scribbleMouseDown, false);
canvas.addEventListener('mousemove', scribbleMouseMove, false);
canvas.addEventListener('mouseup', scribbleMouseUp, false);
canvas.addEventListener('touchstart', scribbleTouchStart, false);
canvas.addEventListener('touchend', scribbleTouchEnd, false);
canvas.addEventListener('touchmove', scribbleTouchMove, false);
function drawLine(ctx, x, y, size) {
if (lastX == -1) {
lastX = x;
lastY = y;
}
ctx.strokeStyle = "#000000";
ctx.lineCap = "round";
ctx.lineWidth = size;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.stroke();
ctx.closePath();
lastX = x;
lastY = y;
}
function scribbleMouseDown() {
mouseDown = 1;
drawLine(ctx, mouseX, mouseY, 3);
}
function scribbleMouseUp() {
mouseDown = 0;
lastX = -1;
lastY = -1;
}
function scribbleMouseMove(e) {
getMousePos(e);
if (mouseDown == 1) {
drawLine(ctx, mouseX, mouseY, 3);
}
}
function getMousePos(e) {
if (!e) {
var e = event;
}
if (e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
} else if (e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
}
function scribbleTouchStart() {
getTouchPos();
drawLine(ctx, touchX, touchY, 3);
event.preventDefault();
}
function scribbleTouchEnd() {
lastX = -1;
lastY = -1;
}
function scribbleTouchMove(e) {
getTouchPos(e);
drawLine(ctx, touchX, touchY, 3);
event.preventDefault();
}
function getTouchPos(e) {
if (!e) {
var e = event;
}
if (e.touches) {
if (e.touches.length == 1) {
var touch = e.touches[0];
touchX = touch.pageX - touch.target.offsetLeft;
touchY = touch.pageY - touch.target.offsetTop;
}
}
}
function crop(canvas) {
var w = canvas.width,
h = canvas.height;
var pix = {
x: [],
y: []
};
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var x, y, index;
for (y = 0; y < h; y++) {
for (x = 0; x < w; x++) {
index = (y * w + x) * 4;
if (imageData.data[index + 3] > 0) {
pix.x.push(x);
pix.y.push(y);
}
}
}
pix.x.sort(function(a, b) {
return a - b
});
pix.y.sort(function(a, b) {
return a - b
});
if (pix.x.length == 0) {
return '#';
}
var n = pix.x.length - 1;
w = 1 + pix.x[n] - pix.x[0];
h = 1 + pix.y[n] - pix.y[0];
var cut = ctx.getImageData(pix.x[0], pix.y[0], w, h);
//document.body.style.opacity = 0;
canvas.width = w;
canvas.height = h;
ctx.putImageData(cut, 0, 0);
return canvas.toDataURL();
}
document.getElementById('scribble-submit').addEventListener('click', function(e) {
e.preventDefault();
var data = crop(document.querySelector('#scribble-canvas'));
document.getElementById('scribble-result').setAttribute('src', data);
});
<html>
<body>
<canvas id="scribble-canvas" style="width:200; height:200; border: 1px solid blue;"></canvas>
<br>
<button id="scribble-submit">
Run
</button>
<br>
Output:
<br>
<img src="#" id="scribble-result" />
</body>
</html>
You either send the wrong data or use different data to render.
If you are saving into a .png file, you may want to strip out the initial data:image/png;base64, before turning that into bytes.

How do I implement a click counter/scorekeeper with ONLY JS (if it is possible)?

I am trying to finish the main framework of a computer game that I am creating and am trying to implement "scores" or values into it to make it more functional.
I have some basic code that actually works, but not exactly how I want to.
Here is the code that I have been using (all the variables have been declared)
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 600;
this.canvas.height = 480;
//this.canvas.style.cursor = "none"; //hide the original cursor
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 1);
window.addEventListener('mousedown', function (e) {
myGameArea.x = e.pageX;
myGameArea.y = e.pageY;
console.log("hello");
});
window.addEventListener('mouseup', function (e) {
myGameArea.x = false;
myGameArea.y = false;
});
},
clear : function(){
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
if (this.type == "text") {
ctx.font = this.width + " " + this.height;
ctx.fillStyle = color;
ctx.fillText(this.text, this.x, this.y);
} else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
this.clicked = function() {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var clicked = true;
if ((mybottom < myGameArea.y) || (mytop > myGameArea.y) || (myright < myGameArea.x) || (myleft > myGameArea.x)) {
clicked = false;
}
return clicked;
}
}
function updateGameArea() {
myGameArea.clear();
if (myGameArea.x && myGameArea.y) {
if (item1.clicked()) {
console.log("red square says hi");
myScore = myScore + 1;
}
if (item2.clicked()) {
console.log("orange square says hi");
}
if (item3.clicked()) {
console.log("yellow square says hi");
}
if (item4.clicked()) {
console.log("green square says hi");
}
if (item5.clicked()) {
console.log("blue square says hi");
}
if (item6.clicked()) {
console.log("purple square says hi");
}
}
scoreDisplay.text = "Score: " + myScore;
scoreDisplay.update();
myGamePiece.update();
item1.update();
item2.update();
item3.update();
item4.update();
item5.update();
item6.update();
itemArea.update();
orderScreen.update();
}
When I click the red square(item1) the score increases, but it doesn't stop until I stop clicking or my mouse is up. I want my code to simply increase the value once per click of the object instead of increasing when the mouse is down.
The logic behind what you want to happen is pretty much this :
JavaScript :
var i = 0;
function addPoint() {
if (document.getElementById("value").value != null) {
document.getElementById("value").value = ++i;
} else { return false }
}
HTML :
<button onclick="addPoint()">+1 Point</button>
<input type="text" id="value" value="0"></input>
If you want a more "complete" approach, you could do this on the JavaScript part :
function addPoint() {
var addValue = parseInt(document.getElementById("value").value, 10);
addValue = isNaN(addValue) ? 0 : addValue;
addValue++;
document.getElementById("value").value = addValue;
}
Use an event listener like you did for the events mousedown
and mouseup:
This will capture every click inside your canvas, not outside.
Define a variable in your myGameArea object:
var myGameArea = {
canvas : document.createElement("canvas"),
clicks : 0, //HERE
start : function() {
this.canvas.width = 600;
this.canvas.height = 480;
...
And then, add the event listener on the start() function:
var myGameArea = {
canvas : document.createElement("canvas"),
clicks : 0,
start : function() {
this.canvas.width = 600;
this.canvas.height = 480;
//this.canvas.style.cursor = "none"; //hide the original cursor
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 1);
window.addEventListener('mousedown', function (e) {
myGameArea.x = e.pageX;
myGameArea.y = e.pageY;
console.log("hello");
});
this.canvas.addEventListener("click",(e)=>{ // Use ES6 arrow function
this.clicks++;
});
...
Take a look at an example:
var myGameArea = {
canvas : document.querySelector("canvas"),
clicks : 0,
start : function(){
this.canvas.addEventListener("click",(e)=>{ // Use ES6 arrow function
this.clicks++;
console.log(`Click+1, now = ${this.clicks}`);
});
}
};
myGameArea.start();
canvas{
background: black;
}
<canvas width="300" height="300"></canvas>

JavaScript Canvas create square [duplicate]

This question already has an answer here:
Drawing a rectangle on Canvas
(1 answer)
Closed 5 years ago.
I want to draw a square with a function like following.
How can I modify following function to create a square.
function square() {
var tool = this;
this.started = false;
this.mousedown = function (ev) {
context.beginPath();
context.moveTo(ev._x, ev._y);
tool.started = true;
};
this.mousemove = function (ev) {
if (tool.started && checkboxSquare.checked) {
context.lineTo(ev._x, ev._y);
context.stroke();
}
};
this.mouseup = function (ev) {
if (tool.started && checkboxSquare.checked) {
tool.mousemove(ev);
tool.started = false;
}
};
}
Here is a rework:
var Square;
(function(Square) {
var canvas = document.body.appendChild(document.createElement("canvas"));
canvas.style.border = "1px solid";
canvas.width = 800;
canvas.height = 800;
var context = canvas.getContext("2d");
var drawing = false;
var square = {
x: 0,
y: 0,
w: 0,
h: 0,
color: getColor()
};
var persistentSquares = [];
function getColor() {
return "rgb(" +
Math.round(Math.random() * 255) + ", " +
Math.round(Math.random() * 255) + ", " +
Math.round(Math.random() * 255) + ")";
}
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
for (var pSquareIndex = 0; pSquareIndex < persistentSquares.length; pSquareIndex++) {
var pSquare = persistentSquares[pSquareIndex];
context.fillStyle = pSquare.color;
context.fillRect(pSquare.x, pSquare.y, pSquare.w - pSquare.x, pSquare.h - pSquare.y);
context.strokeRect(pSquare.x, pSquare.y, pSquare.w - pSquare.x, pSquare.h - pSquare.y);
}
context.strokeRect(square.x, square.y, square.w - square.x, square.h - square.y);
}
canvas.onmousedown = function(evt) {
square.x = evt.offsetX;
square.y = evt.offsetY;
square.w = evt.offsetX;
square.h = evt.offsetY;
drawing = true;
requestAnimationFrame(draw);
};
canvas.onmousemove = function(evt) {
if (drawing) {
square.w = evt.offsetX;
square.h = evt.offsetY;
requestAnimationFrame(draw);
}
};
function leave(evt) {
if (!drawing) {
return;
}
square.w = evt.offsetX;
square.h = evt.offsetY;
drawing = false;
persistentSquares.push(square);
square = {
x: 0,
y: 0,
w: 0,
h: 0,
color: getColor()
};
requestAnimationFrame(draw);
};
canvas.onmouseup = leave;
canvas.onmouseleave = leave;
})(Square || (Square = {}));
It's your lucky day! I was just working on something like this. If you use it for anything, be sure to credit me! ;)
Note that circle and oval are still a Work in Progress.
Link to JSFiddle that will be updated when I update the program: JSFiddle
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var mx=300;
var my=300;
var currentObject = {};
document.onmousemove = function(e){
mx=e.pageX-8;
my=e.pageY-8;
}
document.onmousedown = function(e){
var obj = document.getElementById("objSel").value;
currentObject.type=obj;
if(obj=="Rectangle"||currentObject.type=="Square"){
currentObject.x=e.pageX-8;
currentObject.y=e.pageY-8;
}
}
document.onmouseup = function(e){
mx=e.pageX-8;
my=e.pageY-8;
objects.push(complete(currentObject));
currentObject={};
}
var objects = [];
function render(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.moveTo(mx-5,my);
ctx.lineTo(mx+5,my);
ctx.moveTo(mx,my-5);
ctx.lineTo(mx,my+5);
ctx.strokeStyle="black";
ctx.lineWidth=2;
ctx.stroke();
ctx.closePath();
if(currentObject.type=="Rectangle"){
ctx.beginPath();
ctx.rect(currentObject.x,currentObject.y,mx-currentObject.x,my-currentObject.y);
ctx.stroke();
}
draw(complete(currentObject));
for(var i=0;i<objects.length;i++){
draw(objects[i]);
}
}
setInterval(render,5);
render();
function complete(o){
if(o.type=="Square"){
var sidelength = Math.max(Math.abs(mx-o.x),Math.abs(my-o.y));
var fix = function(input){
if(input==0){
return 1;
} else {
return input;
}
};
o.length=fix(Math.sign(mx-o.x))*sidelength;
o.height=fix(Math.sign(my-o.y))*sidelength;
} else if(o.type=="Rectangle"){
o.length=mx-o.x;
o.height=my-o.y;
}
return o;
}
function draw(o){
if(o.type=="Square"||o.type=="Rectangle"){
ctx.beginPath();
ctx.rect(o.x,o.y,o.length,o.height);
ctx.stroke();
}
}
<canvas id="canvas" style="border:1px solid black;" width="500" height="500">Please use a browser that supports the canvas element and make sure your Javascript is working properly.</canvas>
<br>
<span id="testing"></span>
<select id="objSel">
<option>Square</option>
<option>Rectangle</option>
<option>Circle</option>
<option>Oval</option>
</select>

I want to draw one circle on a canvas from an array?

I want to be able to start with draw one circle on my canvas that I push onto an array. This is not working.
function Circle(x, y, r){
this.x = x;
this.y = y;
this.r = r;
}
// create an array
var anArray = [];
// make a circle instance
var aCircle = new Circle(100, 100, 20);
//add it to the array
anArray.push(aCircle);
function drawCircle() {
context.beginPath();
context.arc(anArry[0].x,anArry[0].y,anArry[0].r,0,Math.PI*2,true);
context.closePath();
context.fill();
Code:
<!DOCTYPE HTML>
<html>
<head>
<style>
canvas {
border: 5px solid #999;
background-color: #000000;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<canvas id="myCanvas" width="450" height="610" style="border:3px solid #c3c3c3;">
</canvas>
<script>
var context;
var rightKey = false;
var leftKey = false;
var upKey = false;
var downKey = false;
var block_x;
var block_y;
var block_h = 15;
var block_w = 15;
var imageObj = new Image();
imageObj.src = 'spaceShip.jpg';
function Circle(x, y, r){
this.x = x;
this.y = y;
this.r = r;
}
// create an array
var anArray = [];
// make a circle instance
var aCircle = new Circle(100, 100, 20);
//add it to the array
anArray.push(aCircle);
function drawCircle() {
context.beginPath();
context.arc(anArry[0].x,anArry[0].y,anArry[0].r,0,Math.PI*2,true);
context.closePath();
context.fill();
/*
for(var i=0; i<numCircle; i++) {
canvasContext.fillStyle='#123321;'
drawCircle(anArry[0].x,anArry[0].y,anArry[0].r,canvasContext);
}
*/
}
function drawScore() {
context.fillStyle = "red";
context.font = "bold 16px Arial";
context.fillText("1000", 5, 15);
context.fillStyle = "red";
context.font = "bold 16px Arial";
context.fillText("14500", 200, 15);
}
function drawExtraLives() {
context.drawImage(imageObj, 45, 3);
context.drawImage(imageObj, 60, 3);
context.drawImage(imageObj, 75, 3);
}
function init() {
context = $('#myCanvas')[0].getContext('2d');
WIDTH = $('#myCanvas').width();
HEIGHT = $('#myCanvas').height();
block_x = WIDTH / 2 - 15;
block_y = HEIGHT / 2 - 15;
setInterval('draw()', 25);
}
function clearCanvas() {
context.clearRect(0,0,WIDTH,HEIGHT);
}
function rect(x,y,w,h) {
context.beginPath();
context.rect(x,y,w,h);
context.endPath();
}
function draw() {
clearCanvas();
if (rightKey)
block_x += 5;
else if (leftKey)
block_x -= 5;
if (upKey)
block_y -= 5;
else if (downKey)
block_y += 5;
if (block_x <= 0)
block_x = 0;
if ((block_x + block_w) >= WIDTH)
block_x = WIDTH - block_w;
if (block_y <= 530)
block_y = 532;
if ((block_y + block_h) >= HEIGHT)
block_y = HEIGHT - block_h;
//all items that have to be redrawn go here.
drawScore();
drawExtraLives();
//drawCircle();
drawGameBottomLine();
context.drawImage(imageObj, block_x,block_y);
//context.fillRect(block_x,block_y,block_w,block_h);
}
function onKeyDown(evt) {
if (evt.keyCode == 39) rightKey = true;
else if (evt.keyCode == 37) leftKey = true;
if (evt.keyCode == 38) upKey = true;
else if (evt.keyCode == 40) downKey = true;
}
function onKeyUp(evt) {
if (evt.keyCode == 39) rightKey = false;
else if (evt.keyCode == 37) leftKey = false;
if (evt.keyCode == 38) upKey = false;
else if (evt.keyCode == 40) downKey = false;
}
function drawGameBottomLine() {
context.beginPath();
context.moveTo(0,530);
context.lineTo(450,530);
context.strokeStyle = 'yellow';
context.stroke();
}
$(document).keydown(onKeyDown);
$(document).keyup(onKeyUp);
init(); //This method sets up the init for the whole game (all things that have to be redraw will be in the draw method.
</script>
</body>
</html>
All code here
<!DOCTYPE HTML>
<html>
<head>
<style>
canvas {
border: 5px solid #999;
background-color: #000000;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<canvas id="myCanvas" width="450" height="610" style="border:3px solid #c3c3c3;">
</canvas>
<script>
var context;
var rightKey = false;
var leftKey = false;
var upKey = false;
var downKey = false;
var block_x;
var block_y;
var block_h = 15;
var block_w = 15;
var shipCnt = 4; //keeps track of the number of ships that the player has left
var levelCnt = 1; //keeps track of which level the player is on so that the correct colored mushroom is displayed
var PLAYERNUM = 'PLAYER 1';
var READY = 'READY!'; //Used to display on the start of every new life
var imageObj = new Image();
imageObj.src = 'spaceShip.jpg';
function Circle(x, y, r){
this.x = x;
this.y = y;
this.r = r;
}
// create an array
var anArray = [];
// make a circle instance
var aCircle = new Circle(100, 100, 20);
//add it to the array
anArray.push(aCircle);
function drawCircle() {
context.beginPath();
context.arc(anArray[0].x, anArray[0].y, anArray[0].r, 0, Math.PI*2, false);
context.fillStyle = 'yellow';
context.fill();
//context.closePath();
/*
for(var i=0; i<numCircle; i++) {
canvasContext.fillStyle='#123321;'
drawCircle(anArry[0].x,anArry[0].y,anArry[0].r,canvasContext);
}
*/
}
function drawScore() {
context.fillStyle = "red";
context.font = "bold 16px Arial";
context.fillText("1000", 5, 15);
context.fillStyle = "red";
context.font = "bold 16px Arial";
context.fillText("14500", 200, 15);
}
function drawExtraLives() {
context.drawImage(imageObj, 45, 3);
context.drawImage(imageObj, 60, 3);
context.drawImage(imageObj, 75, 3);
}
function drawPlayerOne() {
context.fillStyle = "yellow";
context.font = "bold 20px Arial";
context.fillText(PLAYERNUM, 175, 260);
}
function drawReady() {
context.fillStyle = "yellow";
context.font = "bold 20px Arial";
context.fillText(READY, 185, 280);
}
function init() {
context = $('#myCanvas')[0].getContext('2d');
WIDTH = $('#myCanvas').width();
HEIGHT = $('#myCanvas').height();
block_x = WIDTH / 2 - 15;
block_y = HEIGHT / 2 - 15;
setInterval('draw()', 25);
}
function clearCanvas() {
context.clearRect(0,0,WIDTH,HEIGHT);
}
function rect(x,y,w,h) {
context.beginPath();
context.rect(x,y,w,h);
context.endPath();
}
function onKeyDown(evt) {
if (evt.keyCode == 39) rightKey = true;
else if (evt.keyCode == 37) leftKey = true;
if (evt.keyCode == 38) upKey = true;
else if (evt.keyCode == 40) downKey = true;
}
function onKeyUp(evt) {
if (evt.keyCode == 39) rightKey = false;
else if (evt.keyCode == 37) leftKey = false;
if (evt.keyCode == 38) upKey = false;
else if (evt.keyCode == 40) downKey = false;
}
function drawGameBottomLine() {
context.beginPath();
context.moveTo(0,530);
context.lineTo(450,530);
context.strokeStyle = 'yellow';
context.stroke();
}
function draw() {
clearCanvas();
if (rightKey)
block_x += 5;
else if (leftKey)
block_x -= 5;
if (upKey)
block_y -= 5;
else if (downKey)
block_y += 5;
if (block_x <= 0)
block_x = 0;
if ((block_x + block_w) >= WIDTH)
block_x = WIDTH - block_w;
if (block_y <= 530)
block_y = 532;
if ((block_y + block_h) >= HEIGHT)
block_y = HEIGHT - block_h;
//all items that have to be redrawn go here.
drawScore();
drawExtraLives();
drawPlayerOne();
drawReady();
//drawCircle();
drawGameBottomLine();
context.drawImage(imageObj, block_x,block_y);
//context.fillRect(block_x,block_y,block_w,block_h);
}
$(document).keydown(onKeyDown);
$(document).keyup(onKeyUp);
init(); //This method sets up the init for the whole game (all things that have to be redraw will be in the draw method.
</script>
</body>
</html>
You have a syntax error in your drawCircle() method (anArry<>anArray), here is updated code which worked for me:
function drawCircle() {
context.beginPath();
context.arc(anArray[0].x, anArray[0].y, anArray[0].r, 0, Math.PI*2, false);
context.fillStyle = 'yellow';
context.fill();
//context.closePath();
/*
for(var i=0; i<numCircle; i++) {
canvasContext.fillStyle='#123321;'
drawCircle(anArry[0].x,anArry[0].y,anArry[0].r,canvasContext);
}
*/
}
also it is better to put your script into page <head> and call init() as <body onload="init()"> to be sure all resources are loaded when your script runs. (alternatively window.onload = init;)
Nice tutorials where you can edit & run examples is here: http://www.html5canvastutorials.com/tutorials/html5-canvas-circles/

Capture user input on HTML canvas/Javascript and vice versa

I am trying to draw a rectangle in HTML5 canvas based on user input. I am also trying to do the opposite. If a user draws a rectangle in the canvas, the width and height values are dropped into the form. Please see my jsfiddle.
http://jsfiddle.net/hbrennan72/FyTx5/
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var rect = {};
//var drag = false;
function getarea()
{
var wid = document.getElementById("wid").value;
var hgt = document.getElementById("hgt").value;
var area = wid * hgt;
var perim = wid * 2 + hgt * 2;
if (wid =="") {
document.getElementById("errors").innerHTML = "The value for the width is blank.";
document.getElementById('wid').focus();
}
else if (hgt == "") {
document.getElementById("errors").innerHTML = "The value for the height is blank.";
document.getElementById("hgt").focus();
}
else if (isNaN (wid)) {
document.getElementById("errors").innerHTML = "Please enter a numeric value for the width.";
document.getElementById('wid').focus();
}
else if (isNaN (hgt)) {
document.getElementById("errors").innerHTML = "Please enter a numeric value for the height.";
document.getElementById("hgt").focus();
}
else if (wid <= 0) {
document.getElementById("errors").innerHTML = "The width is less than or equal to zero.";
document.getElementById('wid').focus();
}
else if (hgt <= 0) {
document.getElementById("errors").innerHTML = "The height is less than or equal to zero.";
document.getElementById("hgt").focus();
}
else if (wid > 500) {
document.getElementById("errors").innerHTML = "The width is greater than 500.";
document.getElementById('wid').focus();
}
else if (hgt > 500) {
document.getElementById("errors").innerHTML = "The height is greater than 500.";
document.getElementById("hgt").focus();
}
else {
window.document.getElementById("area").innerHTML = area;
window.document.getElementById("perim").innerHTML = perim;
document.getElementById("errors").innerHTML = "Please see results listed above.";
}
}
function updateform (){
"use strict"
var wid = document.getElementById("wid").value;
var hgt = document.getElementById("hgt").value;
var area = wid * hgt;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2D");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(0,0, rect.wid, rect.hgt);
context.fillStyle = "#FF0000"; //red color
draw();
}
function mouseDown(e)
{
rect.startX = e.pageX - this.offsetLeft;
rect.startY = e.pageY - this.offsetTop;
canvas.style.cursor="crosshair";
drag = true;
}
function mouseUp () {
drag = false;
}
function mouseMove(e) {
if (drag) {
rect.wid = (e.pageX - this.offsetLeft) - rect.startX;
rect.hgt = (e.pageY - this.offsetTop) - rect.startY ;
context.clearRect(0,0,canvas.width,canvas.height);
draw();
}
}
function init() {
canvas.addEventListener("mousedown", mouseDown, false);
canvas.addEventListener("mouseup", mouseUp, false);
canvas.addEventListener("mousemove", mouseMove, false);
}
init();
function drawform() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2D");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(0,0, rect.wid, rect.hgt);
context.fillStyle = "#FF0000"; //red color
}
function draw (){
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(rect.startX, rect.startY, rect.wid, rect.hgt);
context.fillStyle = "#378E37"; //green color
}
draw();
I have tried to do it in this way.It is working fine.The code is
$("#smt").click(function(){
var canvasel=' <canvas id="myCanvas" width="400" height="400"></canvas>'
$("#canvas").append(canvasel)
var w=$("#wid").val();
var h=$("#hgt").val();
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,w,h);
ctx.stroke();
})
$("#clr").click(function(){
$("#canvas").empty();
$("#wid").val('');
$("#hgt").val('');
})
initDraw(document.getElementById('canvas'));
function initDraw(canvas) {
function setMousePosition(e) {
var ev = e || window.event; //Moz || IE
if (ev.pageX) { //Moz
mouse.x = ev.pageX + window.pageXOffset;
mouse.y = ev.pageY + window.pageYOffset;
} else if (ev.clientX) { //IE
mouse.x = ev.clientX + document.body.scrollLeft;
mouse.y = ev.clientY + document.body.scrollTop;
}
};
var mouse = {
x: 0,
y: 0,
startX: 0,
startY: 0
};
var element = null;
canvas.onmousemove = function (e) {
setMousePosition();
if (element !== null) {
element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
}
}
canvas.onclick = function (e) {
if (element !== null) {
element = null;
canvas.style.cursor = "default";
console.log("finsihed.");
var width=$(".rectangle").width();
var height=$(".rectangle").height();
$("#wid").val(width);
$("#hgt").val(height)
} else {
console.log("begun.");
mouse.startX = mouse.x;
mouse.startY = mouse.y;
element = document.createElement('div');
element.className = 'rectangle'
element.style.left = mouse.x + 'px';
element.style.top = mouse.y + 'px';
canvas.appendChild(element)
canvas.style.cursor = "crosshair";
}
}
}
SEE DEMO HERE
NOTE:Its not working in Mozilla. I am trying to fix it.Check in Chrome

Categories

Resources