HTML5 Canvas object oriented - javascript

Hi im trying to create a stock bar chart using html5 canvas, first I've decided to create bar object with different methods but can't make it work. Generated bar object does not appears
This is my code:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="1024" height="600" style="border:3px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var context = document.getElementById("myCanvas").getContext("2d");
function Bar(time,open,high,low,close,dir){
vertcord=time
openC=open
highC=high
lowC=low
closeC=close
line_width=8
bar_col='#ff0000'
if (dir==1){
bar_col='#ace600'
}
this.moveTo(vertcord,highC);
this.lineTo(vertcord,lowC);
this.moveTo(vertcord-line_width/2,closeC);
this.lineTo(vertcord+30,closeC);
this.lineWidth = line_width
this.strokeStyle = bar_col;
this.stroke();
}
for (i=0; i < 300; i++) {
tempShape = new Bar(450+i,0,200,100,150,1);
tempShape.drawToContext(context);
}
</script>
</body>
</html>

function Bar(time,open,high,low,close,dir){
this.vertcord = time;
this.openC = open;
this.highC = high;
this.lowC = low;
this.closeC = close;
this.line_width = 8;
this.bar_col = '#ff0000';
if (dir ==1 ) {
this.bar_col = '#ace600';
}
this.drawToContext = function(ctx) {
ctx.moveTo(this.vertcord, this.highC);
ctx.lineTo(this.vertcord, this.lowC);
ctx.moveTo(this.vertcord-this.line_width/2,this.closeC);
ctx.lineTo(this.vertcord+30,this.closeC);
ctx.lineWidth = this.line_width
ctx.strokeStyle = this.bar_col;
ctx.stroke();
}
}
var context = document.getElementById("myCanvas").getContext("2d");
for (i=0; i < 300; i++) {
tempShape = new Bar(450+i,0,200,100,150,1);
tempShape.drawToContext(context);
}
<canvas id="myCanvas" width="1024" height="600" style="border:3px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
I think this is how it supposed to be.You better read a tutorial how to properly implement an object oriented pattern in JavaScript. And learn what "this" means in JavaScript.

Related

How to programmatically free draw using Fabric js?

Building a multiplayer doodle using fabric js.
Trying to implement multiplayer doodle using fabric js, the idea is when U1 draws on canvas we push the points to RTDB and get those points on both the client and programmatically draw the stroke in both the clients.
You can save the canvas' data on path:created for example (or other event) using toJSON().Send it to the server and the other client will load it using loadFromJSON().
Update (4.3.1) (Thanks to #user8555937)
const pointer = canvas.getPointer(e);
const options = {pointer, e:{}} // required for Fabric 4.3.1
canvas2.freeDrawingBrush.onMouseDown(pointer, options);
var canvas = new fabric.Canvas(document.getElementById('canvasId'))
canvas.isDrawingMode = true;
canvas.freeDrawingBrush.width = 5;
canvas.freeDrawingBrush.color = '#00aeff';
canvas.on('path:created', function(e) {
e.path.set();
canvas.renderAll();
drawOnCanvas(canvas.toJSON());
});
var canvas2 = new fabric.Canvas(document.getElementById('canvasId2'));
function drawOnCanvas(json) {
canvas2.loadFromJSON(json);
}
#app {
display: flex;
}
canvas {
border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.19/fabric.min.js"></script>
<div id="app">
<canvas id="canvasId" width="400" height="400"></canvas>
<canvas id="canvasId2" width="400" height="400"></canvas>
</div>
Probably you can optimize it by sending only the diffs and so on, but this is the start of the path
Sync on drawing (not only after path:created)
The idea is to "capture" the "original" canvas' events and trigger them on the second one.
So, you can send the pointer to the server and trigger the events in the other clients.
var canvas = new fabric.Canvas(document.getElementById('canvasId'))
canvas.isDrawingMode = true;
canvas.freeDrawingBrush.width = 5;
canvas.freeDrawingBrush.color = '#00aeff';
let isDrawing = false;
canvas.on('mouse:down', function({e}) {
isDrawing = true;
onMouseDown(e);
}).on('mouse:up', function({e}) {
isDrawing = false;
onMouseUp(e);
}).on('mouse:move', function({e}) {
if (isDrawing) {
const pointer = canvas.getPointer(e);
drawRealTime(e, pointer);
}
});
var canvas2 = new fabric.Canvas(document.getElementById('canvasId2'));
canvas2.isDrawingMode = true;
canvas2.freeDrawingBrush.width = 5;
canvas2.freeDrawingBrush.color = '#00aeff';
function onMouseDown(e) {
const pointer = canvas.getPointer(e);
canvas2.freeDrawingBrush.onMouseDown(pointer);
}
function onMouseUp(e) {
const pointer = canvas.getPointer(e);
canvas2.freeDrawingBrush.onMouseUp(pointer);
}
function drawRealTime(e, pointer) {
canvas2.freeDrawingBrush.onMouseMove(pointer);
}
#app {
display: flex;
}
canvas {
border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.19/fabric.min.js"></script>
<div id="app">
<canvas id="canvasId" width="400" height="400"></canvas>
<canvas id="canvasId2" width="400" height="400"></canvas>
</div>
https://codepen.io/moshfeu/pen/ZEGQEBO?editors=0010

Cell of a minesweeper board does not appear Html&CSS&JS

I am trying to creat a minesweeper board in Javascript, but first i tried to creat only one cell. this is my code. It was suppose to draw a cell from the 30px width and 30px height picture that i created ( cell.png ) but when i run the code i only see the canvas. What am i doing wrong?
<!DOCTYPE html>
<html>
<head>
<script>
var s = {
rows: 10,
col: 10,
width: 30,
height: 30,
};
var c;
window.onload = function(){
var canvas = document.getElementById("myCanvas");
c = canvas.getContext("2d");
// c.fillRect(50,50,300,300);
init();
}
var box;
function init(){
box = new Image();
box.src = "cell.png";
draw();
}
function draw(){
c.clearRect(0,0,400,400);
c.drawImage(box,10,10);
}
</script>
</head>
<body>
<div id="controls">
</div>
<div id="game">
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #c3c3c3;">
</canvas>
</div>
</body>
</html>
The problem you are experiencing is because your code is not waiting for the image to load before trying to draw it. You need to wait till it is loaded then call the drawing code, this can be done from the image's onload event
var s = {
rows: 10,
col: 10,
width: 30,
height: 30,
};
var c;
window.onload = function(){
var canvas = document.getElementById("myCanvas");
c = canvas.getContext("2d");
init();
}
var box;
function init(){
box = new Image();
//onload will be called once the image has loaded
box.onload = function(){
//Here you call draw.
draw();
};
box.src = "http://placehold.it/30x30"; //"cell.png";
}
function draw(){
c.clearRect(0,0,400,400);
c.drawImage(box,10,10);
}
<canvas width="200" height="200" id="myCanvas"></canvas>

Adding Click Event Handler onto Multiple Canvas

I am fairly new to javascript and HTML5, so excuse me if it turns out to be a silly mistake
I am drawing 3 canvas programmatically with some text and a rectangle and i want a click event on each one of them, also I need to know which canvas has been clicked, i wrote the following code but doMouseDown function is executed even without click
<canvas id="myCanvas1" width="452" height="80" style="border:0px solid #d3d3d3;"></canvas>
<canvas id="myCanvas2" width="452" height="80" style="border:0px solid #d3d3d3;"></canvas>
<canvas id="myCanvas3" width="452" height="80" style="border:0px solid #d3d3d3;"></canvas>
<script>
function init()
{
var rect = { w: 300, h: 60 };
var point = { x: 150, y: 10 };
for (var i = 1 ; i < 4 ; i++) {
var canvasStr = "myCanvas" + Number(i);
var c = document.getElementById(canvasStr);
var context = c.getContext("2d");
// text
context.font = "22pt Arial";
context.lineWidth = 2;
context.fillStyle = "#000000";
var studentStr = "Student " + Number(i);
context.fillText(studentStr, 5, 50);
// rectangle
context.strokeStyle = "black";
context.strokeRect(point.x, point.y, rect.w, rect.h);
context.fillStyle = "#00FF00";
context.fillRect(point.x, point.y, rect.w, rect.h);
c.addEventListener('mousedown', doMouseDown(canvasStr), false);
}
}
function doMouseDown(canvasStr)
{
alert(canvasStr);
}
init();
</script>
How can i fix it and know which canvas has been clicked (canvasStr in this case)
You can do it this way
c.addEventListener("mousedown", function () {
doMouseDown(canvasStr)
}, false);
and then write in that function
function doMouseDown(canvasStr) {
alert(canvasStr);
}
if you're attaching listeners in a loop, you have to create a closure, otherwise canvasStr will allways be == myCanvas3:
(function(str) {
c.addEventListener('mousedown', doMouseDown.bind(str), false);
}(canvasStr));
Then your callback should be:
function doMouseDown(e, canvasStr) {
alert(canvasStr);
}
First argument e is the Event object which is always passed to callbacks.
ADDED
There is no point in doing this:
var canvasStr = "myCanvas" + Number(i);
i is already a number and you are adding it to a string. Just write:
var canvasStr = "myCanvas" + i;
Another way is to wrap all 3 canvases in a container div and listen for events on the container
http://jsfiddle.net/m1erickson/g7fsS/
<div id="container">
<canvas id="myCanvas1" width="45" height="80"></canvas>
<canvas id="myCanvas2" width="45" height="80"></canvas>
<canvas id="myCanvas3" width="45" height="80"></canvas>
</div>
document.getElementById("container").addEventListener("click",function(e){
console.log(e.target.id);
},false);

Display image in canvas with Javascript?

I want to be able to click on a button on my page and load an image into a canvas at some X,Y coordinates?
The following code is what I have below. I would like the image to be in either image/photo.jpg or in the same directory but preferably in a subdirectory of the main page.
**Question: How to make a JPG show up in a canvas with the click of a button on the web page?
Code:
<!DOCTYPE html>
<html>
<script>
function draw(){
var ctx = document.getElementById("myCanvas").getContext("2d");
var img = new Image():
// img.src = "2c.jpg";
img.src = "/images/2c.jpg";
ctx.drawImage(img,0,0);
}
</script>
<body background="Black">
<div align="center">
<button type="button" onclick="draw()">Show Image on Canvas</button>
<canvas id="myCanvas" width="900" height="400" style="border:2px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
</div>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="20px Arial";
ctx.fillText("Royal Flush $",500,50);
ctx.fillText("Striaght Flush $",500,80);
ctx.fillText("Flush $",500,110);
ctx.fillText("Four of a Kind $",500,140);
ctx.fillText("Full House $",500,170);
ctx.fillText("Three of a Kind $",500,200);
ctx.fillText("Two Pair $",500,230);
ctx.fillText("Pair of ACES $",500,260);
ctx.rect(495,10,270,350);
ctx.stroke();
</script>
</body>
</html>
March 6th, 2014 Code:
How is the following code not working. Do you have to have an ID tag on Canvas. The page will display but for some reason the image will not when the button is clicked. The image is in the same directory that my index.html file is in.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style type="text/css">
canvas{
border: 5px solid black;
}
</style>
</html>
<button id="galaxy">Add image #1</button>
<button id="circles">Add image #2</button><span></span>
<canvas width="500" height="500"></canvas>
<script>
var Images = {};
function loadImages(list){
var total = 0;
document.querySelector("span").innerText = "...Loading...";
for(var i = 0; i < list.length; i++){
var img = new Image();
Images[list[i].name] = img;
img.onload = function(){
total++;
if(total == list.length){
document.querySelector("span").innerText = "...Loaded.";
}
};
img.src = list[i].url;
}
}
function drawImage(img){
var ctx = document.querySelector("canvas").getContext("2d");
ctx.drawImage(Images[img], 0, 0, 50, 50);
}
loadImages([{
name: "2c.jpg",
url: "mp.jpg"
},{
name: "mp.jpg",
url: "mp.jpg"
}]);
document.querySelector("#galaxy").addEventListener("click", function(){
drawImage("galaxy");
});
document.querySelector("#circles").addEventListener("click", function(){
drawImage("weirdCircles");
});
</script>
</html>
Wait till the image is loaded before drawing:
var img = new Image();
img.onload = function(){ /*or*/ img.addEventListener("load", function(){
ctx.drawImage(img,0,0); ctx.drawImage(img,0,0);
}; };
img.src = "/images/2c.jpg";
Demo: http://jsfiddle.net/DerekL/YcLgw/
If you have more than one image in your game,
It is better to preload all images before it starts.
Preload images: http://jsfiddle.net/DerekL/uCQAH/ (Without jQuery: http://jsfiddle.net/DerekL/Lr9Gb/)
If you are more familiar with OOP: http://jsfiddle.net/DerekL/2F2gu/
function ImageCollection(list, callback){
var total = 0, images = {}; //private :)
for(var i = 0; i < list.length; i++){
var img = new Image();
images[list[i].name] = img;
img.onload = function(){
total++;
if(total == list.length){
callback && callback();
}
};
img.src = list[i].url;
}
this.get = function(name){
return images[name] || (function(){throw "Not exist"})();
};
}
//Create an ImageCollection to load and store my images
var images = new ImageCollection([{
name: "MyImage", url: "//example.com/example.jpg"
}]);
//To pick and draw an image from the collection:
var ctx = document.querySelector("canvas").getContext("2d");
ctx.drawImage(images.get("MyImage"), 0, 0);

Toggle Onclick Issue in Javascript

Simply put, I'm trying to toggle a button to make a line bold (or not). I read a few questions here similar to this problem, but the solutions haven't helped me. Here's my code:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<div id="DrawLineDiv">
<canvas id="DrawLineCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('DrawLineCanvas');
var context = canvas.getContext('2d');
// Use beginPath() to declare that a new path is to be drawn
context.beginPath();
// Place the drawing cursor at the desired point
context.moveTo(100, 150);
// Determine where to stop drawing
context.lineTo(450,50);
//Draw the line
context.stroke();
</script>
</div>
<script>
var canvas = document.getElementById("DrawLineCanvas");
//var context = canvas.getContext('2d');
function toggleLineBold(button) {
var button;
if (button == "BoldNow") {
context.lineWidth = 15;
context.stroke();
document.getElementById("BoldLineButton").onclick = function(){
toggleLineBold('Regular');
};
} else {
context.lineWidth = 1;
context.stroke();
document.getElementById("BoldLineButton").onclick = function(){
toggleLineBold('BoldNow');
};
return;
};
};
</script>
<div id="BoldLineButton" style="height:50px; width:120px; border:2px solid #6495ed; background-color:#bcd2ee; border-radius:10px; margin-left: 5px; text-align:center" onclick="toggleLineBold('BoldNow')">
<br/>Toggle Bold Line<br/>
</div>
</body>
</html>
The line changes to bold, but triggers an error in the javascript at the line trying to change the onclick event. I know I've got something wrong, I'm just not sure what.
Thank's in advance for your assistance.
LIVE DEMO
HTML:
<canvas id="DrawLineCanvas" width="578" height="200"></canvas>
<button id="BoldLineButton">Line size: <b>1</b></button>
JS:
var doc = document,
canvas = doc.querySelector('#DrawLineCanvas'),
boldBtn = doc.querySelector('#BoldLineButton'),
ctx = canvas.getContext('2d'),
size = [1, 3, 5, 10, 15], // use only [1, 15] if you want
currSize = 0; // size[0] = 1 // Index pointer to get the value out of the
// size Array
function draw(){
canvas.width = canvas.width;
ctx.beginPath();
ctx.moveTo(100, 150);
ctx.lineTo(450,50);
ctx.lineWidth = size[currSize]; // Use currSize Array index
ctx.stroke();
}
draw();
function toggleLineBold() {
++currSize; // Increase size and
currSize %= size.length; // loop if needed.
boldBtn.getElementsByTagName('b')[0].innerHTML = size[currSize];
draw();
}
boldBtn.addEventListener("click", toggleLineBold);

Categories