Add canvas attributes dynamically? - javascript

Say I have the canvas tag in my HTML5 document
<canvas id="fooBar" width="500" height="200"></canvas>
And I also have an empty anchor tag
Spin
and I build my canvas in the head
var fooCanvas = document.getElementById("fooBar");
var barContext = fooCanvas.getContext("2d");
Is there a way I can add:
barContext.fillText("fubar", x,y);
Dynamically via clicking on the anchor tag? What I want is to have a variable in my JS which doesn't always hold the same value, and clicking the a tag would update the canvas fillText attribute every time the link is clicked, My idea to overcome this is to use jQuery and have something like this:
$(document).ready(function(){
$("a").click(function(event){
// Something here
});
});
Obviously this would work on every a tag I have in the document so I'll specify that later on but I'm not too sure on the syntax required to append that canvas attribute to my canvas? Any ideas?

Yes:
var fooCanvas = document.getElementById("fooBar");
var barContext = fooCanvas.getContext("2d");
$(document).ready(function(){
$("a").click(function(event){
barContext.fillText("fubar", x,y);
});
});
Although you might want to use button elements instead of a, since they're not actually links.

Related

jQuery remove or hide all svg on the canvas

I want to remove or hide the svg I double click on.
var draw = SVG('output').size(1000, 500);
var table = draw.circle(50)
.fill('#00ff0000')
.stroke('black')]
.center(50, 50);
table.attr("class", "table");
$("svg").on('dblclick',function(event){
$(".table").hide();
});
var desk = draw.rect(50,50)
.fill('green')
.stroke('black')
.move(100,0);
desk.attr("class", "desk");
$("svg").on('dblclick',function(event){
$(".desk").hide();
});
var chair = draw.rect(50,50)
.fill('green')
.stroke('black')
.move(200,0);
desk.attr("class", "chair");
$("svg").on('dblclick',function(event){
$(".chair").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.3/svg.min.js"></script>
<div id="output"></div>
I want to hide the one that I double click on, but now the result is that, all of them are hidden if I double click any one of them. Even if I double click the blank space of canvas, all of the SVG images are also hidden.
When you write $("svg"), that targets every single svg element on the page.
When this code runs $("svg").on('dblclick',function(event){ $(".table").hide(); }); for example,
every SVG on the page gets the "dblclick" event to hide ".table". To solve this, instead of globally selecting all svg elements, use CSS selectors https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors to only grab the svg related to the class you give it (e.g. maybe you want $("svg.table").on('dblclick') or something like that)

exporting ng2-chart canvas to png image

I would like to create a link to allow the user to download the displayed graph. The way i am currently trying to get it to work is with .toDataUrl is that considered a safe way or is there another way of going about doing this.
HTML:
<canvas id="myChart" baseChart [colors]="colorsOverride" [datasets]="barChartData" [labels]="barChartLabels" [options]="barChartOptions" [legend]="barChartLegend"
[chartType]="barChartType" (chartHover)="chartHovered($event)" (chartClick)="chartClicked($event)">
</canvas>
<div class="footer">
<button (click)="exportGraph()">Export Graph</button>
</div>
Components:
export_graph = <HTMLCanvasElement>document.getElementById("myChart");
downloadLink: string;
exportGraph(){
this.downloadLink = this.export_graph.toDataURL("image/png");
}
When i try to export this is the error message i get in my console:
Cannot read property 'toDataURL' of null
You should use an anchor tag <a> instead of <button>, you can style it to look just like a button. Then you can attach a click event and do it this way:
plunker: http://plnkr.co/edit/xyfWok58R3eQdYk7pAds?p=preview
first, add the download link to your html
DOWNLOAD THIS
then create the downloadCanvas function
downloadCanvas(event) {
// get the `<a>` element from click event
var anchor = event.target;
// get the canvas, I'm getting it by tag name, you can do by id
// and set the href of the anchor to the canvas dataUrl
anchor.href = document.getElementsByTagName('canvas')[0].toDataURL();
// set the anchors 'download' attibute (name of the file to be downloaded)
anchor.download = "test.png";
}
it is important to do the document.getElement... on click instead of before-hand. This way you know for sure the html view and <canvas> has rendered and is done drawing (you see it on the page).
the way you are doing it in your question, you are looking for <canvas> element before it's even rendered on the page, that why it's undefined.

Change the background image of an element

So I'm having some issues with creating a really simple function that's supposed to change the background image of a div element to match whatever image is being hovered upon by the mouse.
The HTML looks like
<div id = "image">
Hover over an image below to display here.
</div>
<img class = "preview" alt = "Styling with a Bandana" src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg" onmouseover = "upDate(this)" onmouseout = "unDo()">
That's just the div element I want to change, alongside one of the images.
So our function is supposed to take in an image element as a parameter. But I'm having a lot of trouble accessing this image parameter's src attribute and using that in the .style.backgroundImage property.
My current code is:
function upDate(previewPic){
var div_element = document.getElementById('image').innerHTML;
var picurl = "url(previewPic.getAttribute('src'))"
div_element.style.backgroundImage = "url(picurl)";
}
And this gets me an error of Uncaught TypeError: Cannot set property 'backgroundImage' of undefined on my browser console.
If you can tell, I'm trying to put the actual div object into a variable, then put the picture url into a variable. Then I want to use the .style.backgroundImage property. This isn't working. But the solution is probably really simple. What could I do to fix it?
There are multiple issues with your code.
Getting the inner html is just setting your variable to a string representation of what's inside the element, which is nothing since it's an <img> tag.
Essentially, you're putting everything in quotes, so javascript doesn't do anything with it.
Remove the .innerHTML from the first line of the function, and then take the parts javascript needs to evaluate as code out of the quotes.
Change your code to:
function upDate(previewPic){
var div_element = document.getElementById('image');
var picurl = "url(" + previewPic.getAttribute('src') +")"
div_element.style.backgroundImage = picurl;
}
This should work.
If I understand on some image hover you want to change div background?
I would do it with jquery:
$('img').hover(function(){
$('div').css(''background-image:'url("image_link")');
});

get the html of element itself using jquery .html()

How to get the html of element itself using Jquery html. In the below code I would like get the input element inside div using JQuery as shwon below
<div id="content">content div</div>
<input type='text' id="scheduledDate" class="datetime" />
$(function() {
console.log($('#scheduledDate').html('dsadasdasd'));
$('#content').html($('#scheduledDate').html());
});
EDIT:
Can I get the $("#scheduledDate") as string which represent the real html code of the input box, because my final requirement is I want to pass it to some other SubView( I am using backboneJS) and eventually use that html code in a dust file.
My original requirement was to get that input field as string so that I can pass it to some other function. I know, if I keep it inside a DIV or some other container, I can get the html by using .html method of JQuery. I dont want use some other for that purpose. I am just trying to get html content of the input box itself using it's id.
If you want to move the input element into div, try this:
$('#content').append($('#scheduledDate'));
If you want to copy the input element into div, try this:
$('#content').append($('#scheduledDate').clone());
Note: after move or copy element, the event listener may need be registered again.
$(function() {
var content = $('#content');
var scheduledDate = $('#scheduledDate');
content.empty();
content.append(scheduledDate.clone());
});
As the original author has stated that they explicitly want the html of the input:
$(function() {
var scheduledDate = $('#scheduledDate').clone();
var temporaryElement = $('<div></div>');
var scheduleDateAsString = temporaryElement.append(scheduledDate).html();
// do what you want with the html such as log it
console.log(scheduleDateAsString);
// or store it back into #content
$('#content').empty().append(scheduleDateAsString);
});
Is how I would implement this. See below for a working example:
https://jsfiddle.net/wzy168xy/2/
A plain or pure JavaScript method, can do better...
scheduledDate.outerHTML //HTML5
or calling by
document.getElementById("scheduledDate").outerHTML //HTML4.01 -FF.
should do/return the same, e.g.:
>> '<input id="scheduledDate" type="text" value="" calss="datetime">'
if this, is what you are asking for
fiddle
p.s.: what do you mean by "calss" ? :-)
This can be done the following ways:
1.Input box moved to the div and the div content remains along with the added input
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").append($inputBox);
});
2.The div is replaced with the copy of the input box(as nnn pointed out)
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
var $clonedInputBox = $("#scheduledDate").clone();
$("#content").html($clonedInputBox);
});
Div is replaced by the original input box
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").html($inputBox);
});
https://jsfiddle.net/atg5m6ym/4485/
EDIT 1:
to get the input html as string inside the div itself use this
$("#scheduledDate").prop('outerHTML')
This will give the input objects html as string
Check this js fiddle and tell if this is what you need
https://jsfiddle.net/atg5m6ym/4496/

remove html tag using jquery/javascript

I have an html element on my website that is being put there beyond my control and I need to remove it using javascript/jquery. The HTML tag is consistent and on every page, it looks like this:
<img src="https://myimage.com/myimage.jpg" style="cursor:pointer;border:none;">
how do I remove it? The image has no ID. Thanks so much in advance!
You can remove it like this:
jQuery("img[src='https://myimage.com/myimage.jpg']").remove();
Be sure that that code is in a script tag below the relevant image in the markup of the page. If the image is being added dynamically after the page markup has been parsed, you may have to be more crafty:
(function() {
function removeImage() {
var img = jQuery("img[src='https://myimage.com/myimage.jpg']");
if (img.length) {
// It's there now, remove it
img.remove();
}
else {
// Not there yet, check again in a quarter of a second
setTimeout(removeImage, 250);
}
}
removeImage(); // Start the process
})();
Note: You're removing an element, not a tag. Tags are markup (text). Elements are the result of tags being parsed and created by the browser.
use
$("img[src='https://myimage.com/myimage.jpg']").remove();
That will hide that image
Here you go
$("img[src='https://www.google.com/images/srpr/logo11w.png']").remove();
http://jsfiddle.net/bowenac/GD64n/
Mind explaining what the image is or post a live link? This will remove it from displaying but will not fix the source of the problem if this is some kind of hack placing this code into your files...
No jQuery, plain JS:
var img = document.querySelector('img[src="https://myimage.com/myimage.jpg"]');
if (img) {
img.parentNode.removeChild(img);
}

Categories

Resources