swap graphs on same canvas - javascript

Colleagues,
I have designed a dashboard with HTML canvas and want to show on same page a flot graph, toggling between them with a button.
The problem that I am facing is that when I click to get the flot, the graph shows up under the canvas, and not in the same place (as I want).
This is the relevant code :
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width="800" height="400" style="background-color:#ffffff"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var radio = canvas.height / 2;
var ent_direc={{ent_direc}};
var ent_vel={{ent_vel}};
ctx.translate(radio,radio);
radio_direc = radio * 0.9;
......
function show_graph is called when I click the button
function show_graph(){
// create dynamic DIV to hold graph
var div = document.createElement('div');
div.id = "placeholder";
document.body.appendChild(div) document.getElementById("placeholder").setAttribute("style","width:600px;height:300px");
ctx.save();
// Use the identity matrix while clearing the canvas
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Restore the transform
ctx.restore();
data_g =[ [0,2],[1,4],[2,5]];
$(document).ready(function(){
$.plot($("#placeholder"), [
{
data: data_g ,
bars:
{
show: true
}
}
]);
});
Any idea on how to show the flot graph on the same canvas area?

What you try is not that simple. Flot takes a div element and creates its own canvas elements in this div (and some stuff around the canvas like axis labels).
The easiest solution would be to hide your original canvas when you create the Flot graph:
$('#canvas').hide();

Related

not able to draw rect on existing <canvas> which rendered PDF using pdfjs

Task
Have a canvas in your page
<canvas id="pdfCanvas">
create a fabric canvas for existing canvas
new fabric.Canvas("pdfCanvas");
have mouse.down, mouse.up, mouse.move methods to enable drawing rectangles
render pdf in the above canvas "pdfCanvas" using PDF.js
browser now shows the rendered PDF
now draw rectangles on the pdf, it hides the rendered canvas but it does draw objects
Problem
Here is the fiddle to see the issue:
- run the above https://jsfiddle.net/hiitskiran/wgz8qore/2/
- you can see the fabric rectangle is hiding behind the rendered pdf
- click on the pdf canvas area to see the fabric objects
What I see from your fiddle is that you don't wait the result of page.render method, which is asyncronous, then, unfortunately, if you wait the page.render, the fabric.canvas instance will clean your previously filled canvas, and we can't do nothing for this.
So I tried another approach: First of all, I wait the pdf.js page.render method, then I invoke the .toDataURL of your previously filled canvas so that I can have a copy of the old content, then I set your previously filled canvas as background of your new fabric.canvas and finish to draw your rectangle.
var url = 'http://www.africau.edu/images/default/sample.pdf';
var canvas = document.getElementById('pdfcanvas');
var context = canvas.getContext('2d');
PDFJS.disableWorker = true;
PDFJS.getDocument(url).then(function(pdf) {
pdf.getPage(1).then(function(page) {
var scale = 1.5;
var viewport = page.getViewport(scale);
canvas.height = viewport.height;
canvas.width = viewport.width;
page.render({
canvasContext: context,
viewport: viewport
}).then(function() {
var bg = canvas.toDataURL("image/png");
var fcanvas = new fabric.Canvas("pdfcanvas", {
selection: false
});
fcanvas.setBackgroundImage(bg,fcanvas.renderAll.bind(fcanvas));
fcanvas.setWidth(300);
fcanvas.setHeight(300);
var rect = new fabric.Rect({
left: 100,
top: 100,
width: 50,
height: 50,
fill: '#FF454F',
opacity: 0.5,
transparentCorners: true,
borderColor: "gray",
cornerColor: "gray",
cornerSize: 5
});
fcanvas.add(rect);
fcanvas.renderAll();
});
});
});
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<script src="https://seikichi.github.io/tmp/PDFJS.0.8.715/pdf.min.js"></script>
<canvas id="pdfcanvas" style="border:1px solid black"></canvas>

how to add text area on canvas using jquery javascript

I have a textarea and canvas. The user is able to drag image onto the canvas and change different background images. Now I need to be able to have a section at the bottom of canvas that will display text from textarea.
<canvas id="canvas" width="640" height="280"></canvas>
<div id="text">
<textarea id="write_whatever">Write 4 lines to describe yourself.</textarea>
<div id="button_to_add"></div>
</div>
Here's the jsfiddle of what i currently have http://jsfiddle.net/D4zw4/50/
Here's what I am trying to achieve, but instead of key up it's with button click and it should be at the bottom of the canvas http://jsfiddle.net/m1erickson/NuaHp/
Anyone know how I could achieve this or done this before? Thanks in advance :)
Something like this?
$('#button_to_add').on('click', 'button', function () {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var text = $('#write_whatever').val();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#3e3e3e";
ctx.font = "16px Arial";
ctx.fillText(text, 20, canvas.height - 20);
});
http://jsfiddle.net/D4zw4/51/

Javascript - Putting ImageData Onto a Canvas Element - CanvasRenderingContext2D

I want to take a source image and put its pixel data into a element with a CanvasRenderingContext2D grid.
I'm writing a javascript function to work with certain pixel points of data,
but I keep getting an error from this line:
ctx.putImageData(sourceImage, 0, 0);
Here is my current javascript function that accepts a class ID of an img element as its argument:
function mapMyImage(sourceImageID) {
// Declare variable for my source image
var sourceImage = document.getElementById(sourceImageID);
// Creates a canvas element in the HTML to hold the pixels
var canvas = document.createElement('canvas');
// Create a 2D rendering context for our canvas
var ctx = canvas.getContext('2d');
// After the image has loaded, put the source image data into the
// 2D rendering context grid
function imgToPixelArray() {
// In the context of the canvas, make an array of pixels
ctx.putImageData(sourceImage, 0, 0);
}
// Call the above function once the source image has loaded
sourceImage.onload = imgToPixelArray();
// Get Access to the pixel map now stored in our 2D render
var imageData = ctx.getImageData(0, 0, 400, 300);
}
Why am I getting an error when I am trying to put my source image's pixel data into a 2D rendering context grid?
It looks like you want to clip a 400x300 subsection of the image and draw it into the canvas.
You don't need .getImageData and .putImageData to accomplish that.
You can use the clipping version of .drawImage to do that:
context.drawImage(
img, // the image source
0,0, // start clipping from the source at x=0, y=0
400,300 // clip a subsection that's 400x300 in size
0,0 // draw that clipped subsection on the canvas at x=0,y=0
400,300 // make the drawing 400x300 (don't scale)
)
Here's example code and a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/landscape2.jpg";
function start(){
ctx.drawImage(img, 0,0,400,300, 0,0,400,300);
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<h4>subsection clipped to the canvas</h4>
<canvas id="canvas" width=400 height=300></canvas>
<h4>The original image</h4>
<img src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/landscape2.jpg">

Extract individual frame from a sprite sheet using html or javascript

I have a sprite sheet consisting of 12 frames.
I want to extract each individual frame from it and want to show it in different canvas like below.
what i have tried so far is posted below
//HTML code for define the canvas area .
<body onload="image_render();">
<div id="image_area"> <canvas id="image"></canvas></div>
<script src="sprite_demo.js"></script>
</body>
// javascript to slice the image and assign to the canvas
var canvasImage = new Image();
canvasImage.src = "image/sprite_xxdpi.jpg";
var can= document.getElementById("image");
can.width = 500;
can.height = 300;
function image_render()
{
coin.render();
}
var coin = sprite({
context: can.getContext("2d"),
width: 500,
height: 300,
image: coinImage
});
function sprite (options) {
var that = {};
that.context = options.context;
that.width = options.width;
that.height = options.height;
that.image = options.image;
that.render = function () {
// Draw the animation
that.context.drawImage(
that.image,
0, //X-axis starting position from where slicing begins
0, //y-axis starting position from where slicing begins
that.width, //width of slicing image
that.height,//height of slicing image
0, //X-axis starting position where image will be drawn
0, //y-axis starting position where image will be drawn
150, // width of the resulting image
150); //height of the resulting image
};
return that;
}
I am only able to get a single image ,But I want to get all the images to show in a grid.And also i want to get the image to show any where I want.
I also want to scale down big size images to show in a grid and while taping on it I want to show the original image.
Note: I don't want to animate my frames, I just want to show in grid. There are mostly examples of sprite animation available on internet.
You have the correct version of drawImage to clip individual sprites from the spritesheet, but you must alter the values in drawImage for each sprite.
The "faces" example spritesheet you show appear to have equal sized individual sprites (75px by 75px).
Assuming all your sprites are the same size, you would alter the 2nd & 3rd drawImage parameters which tell canvas the top-left x/y coordinate to begin clipping on the spritesheet.
Here's example code and a Demo: http://jsfiddle.net/m1erickson/tVD2K/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var spriteWidth=75;
var spriteHeight=75;
var spriteCols=4;
var spriteRows=3;
var y=20-sprightHeight;
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/spritesheet1.jpg";
function start(){
var canvasY=0;
for(var col=0;col<spriteCols;col++){
for(var row=0;row<spriteRows;row++){
var sourceX=col*spriteWidth;
var sourceY=row*spriteHeight;
// testing: calc a random position to draw this sprite
// on the canvas
var canvasX=Math.random()*150+20;
canvasY+=spriteHeight+5;
// drawImage with changing source and canvas x/y positions
ctx.drawImage(img,
sourceX,sourceY,spriteWidth,spriteHeight,
canvasX,canvasY,spriteWidth,spriteHeight
);
}}
}
}); // end $(function(){});
</script>
</head>
<body>
<h4>Draw individual sprites from a spritesheet</h4>
<canvas id="canvas" width=300 height=1000></canvas>
</body>
</html>

How to destroy / reload the canvas in html 5?

I am working on an ebook application, I draw each page on canvas using PDF.js , the problem is , when I click on the button and turn to other page, I tried simply render on the same canvas again , but the canvas seems move to a wrong location or wrong size .
function renderPage(url) {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
//clearCanvasGrid('canvas');
PDFJS.getDocument(url).then(function (pdf) {
// Using promise to fetch the page
pdf.getPage(1).then(function(page) {
var viewport = page.getViewport(5); //scale 5
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
page.render(renderContext).then(function() {
initialZoomPage(viewport.height,viewport.width);
});
});
});
}
So, are there any necessary step I need to do before redraw the page? Also , how can I destroy it if I would like to close the page? Thanks
Update:
function clearCanvasGrid(canvasID){
canvas = document.getElementById(canvasID); //because we are looping //each location has its own canvas ID
context = canvas.getContext('2d');
//context.beginPath();
// Store the current transformation matrix
context.save();
// Use the identity matrix while clearing the canvas
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);
// Restore the transform
context.restore(); //CLEARS THE SPECIFIC CANVAS COMPLETELY FOR NEW DRAWING
}
I found a function to clear the canvas but it has .save , .setTransform and .restore besides clearRect, are they necessary? thanks
One way is to clear out the canvas using context.clearRect(0,0, width, height) (Reference).
Alternatively, you can append a new canvas element (and possibly remove the old one, depending on whether you will want to display it again) each time you want a new page. Something like this should do it:
var oldcanv = document.getElementById('canvas');
document.removeChild(oldcanv)
var canv = document.createElement('canvas');
canv.id = 'canvas';
document.body.appendChild(canv);
Just note that if you plan to keep more than one, each one must have a unique id instead of just id="canvas" (perhaps based on the page number - something like canvas-1).
Answer to updated question:
The save, setTransform, and restore are only necessary if you are doing (or somehow allowing users to do) transformation. I don't know if the PDF.js library does any transformation behind the scenes, so it may be best to leave it there.
try using clearRect(), like:
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
In Lightning Aura components, a different approach is required:
The chart object, once created, is stored in an attribute.
<aura:attribute name="chartObject" type="Object"/>
<canvas id="chartId" aura:id="chartCanvas" </canvas>
let theChart = component.get("v.chartObject");
if (theChart != undefined) {
//alternative
//let chartStatus = Chart.getChart("chartId");
//if (chartStatus != undefined) {
//update data if necessary
//theChart.data.datasets[0].data[i] = etc
theChart.update();
}
else{
var ctx = component.find("chartCanvas").getElement();
var chart = new Chart(ctx, {
type: 'line',
data: myData,
options: {
tension: 0.25,
responsive: false,
maintainAspectRatio :false,
fill: true,
}
});
component.set("v.chartObject", chart);
}//endif chart exists

Categories

Resources