Examples I see using <canvas> always have an actual canvas element in the HTML. Say I for example already have a <header> element that I would like to draw on, is there a way to use it as a canvas directly? Or do I need to add that canvas element and make sure it's filling the header?
I was skeptical at first, but there is one way to achieve almost that, by using css and getCSSCanvasContext() with the webkit. This allows you to display a canvas as a background so you can control it like a canvas.
Ex:
HTML
<header></header>
CSS
header { background: -webkit-canvas(fooBar); }
JavaScript (when document ready / onload)
function fillCanvas(w, h) {
var ctx = document.getCSSCanvasContext('2d', 'fooBar', w, h);
// draw into canvas
}
A complete example and more specs are given here.
Hope this is convenient.
Related
I have a very simple question : is it possible to use globalCompositeOperation for only a restricted number of images?
For example, I draw a lot of stuff into my canvas. And on top of everything, and completed unrelated, I want to do some operations on two images (and I just want the result to be displayed, not both images). How can that be done?
For now, doing such operations affects everything that's already drawn underneath.
So a solution I found is doing the operations in another canvas, which I display on top of my main, first canvas. But this looks bad. First, it hits performances. Then, it doesn't feel intuitive. And last, I loose control over the layers : whatever is in my second canvas will always be on top of the first canvas.
This looks like a pretty simple feature, I hope I'm just bad at googling!
Thanks a lot!
Create a offscreen canvas and use it as a work space. You can create many as long as you have the RAM to store them.
To create an offscreen canvas
function createCanvas(w,h){
var canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
canvas.ctx = ctx.getContext("2d");
return canvas;
}
Easy as that and then you just treat it as an image. To draw to another canvas
var offScreenCan = createCanvas(1024,1024);
offScreenCan.ctx.drawImage(myImage); // put something on the canvas
ctx.drawImage(offScreenCan,0,0); // draw that canvas to another
I attach the context to the canvas rather than wrap the canvas in a containing object. I used to worry that the canvas would affect performance now I convert all images to canvas as soon as I load them and it does not impact performance at all.
Background
I've got a bunch of svg's in a document (with rect, path, and whatnot inside each) and I need to draw this out to a downloadable PNG image. I understand that in order to do this there are two methods: either draw the page's HTML structure to a canvas and then export from there or render an SVG and its contents straight onto a canvas.
Hypotheses
The first hypothesis I tried to render the HTML structure using html2canvas and only found out that SVG's could not be rendered via an HTML structure at all (due to security issues). The second hypothesis I tried to render an SVG to canvas via canvg only to find out that it only allowed for one SVG element to be rendered and that only the first one would be rendered.
Results
To prove the first one wrong, type in http://www.w3schools.com/svg/tryit.asp?filename=trysvg_rect to this URL and disable Javascript. To prove the second one wrong I have a fiddle to try out.
The Question
I want to make it clear that my reasoning for having multiple svg's is so that I can place them within a responsive grid system and resize via aspect ratio. Without further ado, I ask my question: How can you render multiple svg elements to a canvas? If the answer to that question is "it isn't possible", then next my question would be: Should I be rendering one svg instead and handle responsiveness another way?
You should be able to draw SVG to canvas just as any other image:
var img1 = document.createElement('img'),
img2 = document.createElement('img')
count = 2;
/// image loading is async, make sure they are loaded
img1.onload = img2.onload = function() {
count--;
if (count === 0) drawImages();
}
img1.src = 'some1.svg';
img2.src = 'some2.svg';
/// when loaded, draw them somewhere on the canvas
function drawImages() {
ctx.drawImage(img1, 0, 0);
ctx.drawImage(img2, someX, someY);
}
That being said - there are a couple of restrictions:
FireFox currently does not want to draw images properly without width and height set inside the SVG file.
CORS (Cross-Origin Resource Sharing) applies if you want to extract images as bitmap (toDataURL/getImageData). If not they should work as normal.
I am having trouble finding a good method to limit my mouse to be only able to click on a pre existing line in canvas (stroke width of 3)
What I need to know
how to limit mouse so can only click on pre- existing line, add a dot on click
line is drawn with this function
function createLine(startX:Float, startY:Float, endX:Float, endY:Float)
{
surface.beginPath();
surface.moveTo(startX, startY);
surface.lineTo(endX, endY);
surface.closePath();
surface.strokeStyle = '#ffffff';
surface.lineWidth = 2;
surface.stroke();
}
I am working in haxe, but solution in JS is fine
Thanks in advance.
The only way is for you to keep track of what you have drawn and do the collision/mouse over detection on your own.
If you need your canvas to be highly interactive, you should probably be looking at SVG. http://raphaeljs.com/ is a great library for drawing which will use canvas or SVG, whichever is available.
Is there any accurate way to get the real size of a svg element that includes stroke, filters or other elements contributing to the element's real size from within Javascript?
I have tried pretty much everything coming to my mind and now I feel I'm coming to a dead end :-(
Updated question to add more context (Javascript)
You can't get the values directly. However, you can get the dimensions of the bounding rectangle:
var el = document.getElementById("yourElement"); // or other selector like querySelector()
var rect = el.getBoundingClientRect(); // get the bounding rectangle
console.log( rect.width );
console.log( rect.height);
It is supported at least in the actual versions of all major browser.
Check fiddle
Both raphael js http://dmitrybaranovskiy.github.io/raphael/ and d3 js http://d3js.org/ have various methods to find the size of an svg object or sets of svg object. It depends on if it's a circle, square, path, etc... as to which method to use.
I suspect you are using complex shapes, so in that case bounding box would be your best bet http://raphaeljs.com/reference.html#Element.getBBox
(Edit: updated reference site.) http://dmitrybaranovskiy.github.io/raphael/reference.html#Element.getBBox
Here is an example using D3.js:
Starting with a div:
<div style="border:1px solid lightgray;"></div>
The javascript code looks like this:
var myDiv = d3.select('div');
var mySvg = myDiv.append('svg');
var myPath = mySvg.append('path');
myPath.attr({
'fill': '#F7931E',
'd': 'M37,17v15H14V17H37z M50,0H0v50h50V0z'
});
// Get height and width.
console.log(myPath.node().getBBox());
If it is an SVG used as a CSS background image and you're using React you can use background-image-size-hook.
import { useBackgroundImageSize } from 'background-image-size-hook'
const App = () => {
const [ref, svg] = useBackgroundImageSize()
console.log(svg) // { width, height, src }
return <SVGBackgroundImageComponent ref={ref} />
}
You didn't specify any programming language. So I can suggest to use Inkscape.
In the file menu you find document's properties and in the first page there's "resize page to content" command. In this way you remove all the white space around your draw and you see the real size. After width and height values apprear inside the header of svg.
I know that Inkscape supports scripting and command line operations but I don't know if it's possible to do the trimming operatation in this way. But if it's possible you can do that from every programming language.
There must be a way to do this. I have drawn a shape with the html5 canvas and I would like to blur it. As far as I know there is no native method so I assume a js library is needed. The problem is most libraries only blur images like this one for example. Is this possible?
myContext.filter = 'blur(10px)';
The CanvasRenderingContext2D.filter property of the Canvas 2D API provides filter effects like blurring or gray-scaling. It is similar to the CSS filter property and accepts the same functions. https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/filter
it's still experimental but is supported by chrome & firefox atm.
You can use CSS to blur the canvas. If it's just the shape you want to blur then the shape will need to be on its own separate layer (canvas), which you could create on the fly.
Example:
canvas.style.webkitFilter = "blur(3px)";
You can un-blur the canvas again with:
canvas.style.webkitFilter = "blur(0px)";
This is probably the fastest (and simplest) way to blur a canvas – especially for mobile devices.
For a fast blur that is almost Gaussian I'd recommend StackBlur:
http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
Alternatively you could use this Superfast Box Blur with 2 iterations:
http://www.quasimondo.com/BoxBlurForCanvas/FastBlurDemo.html
The pixastic library example you've linked to should actually work with a canvas element as the first argument rather than an image.
By default the pixastic library will try to replace the node you pass in with the canvas element that it creates. To prevent it from doing so you can include an option to specify to leave the DOM node and include a callback to handle the returned data yourself. Something like this:
Pixastic.process(canvas, "blur", { leaveDOM: true }, function(img) {
canvas.getContext('2d').drawImage(img, 0, 0);
});
Alternatively, if you don't want to depend on a library, you can implement a blur yourself using getImageData(), manipulating the returned pixel data and using putImageData() to draw the blurred image back to the canvas.
One other thing to note is that individual pixel manipulation is slow and may not work well for large images. If that's a problem, you might try scaling the image down and scaling back up for a quickly done blur like effect. Something like this:
ctx.drawImage(canvas, 0, 0, canvas.width / 2, canvas.height / 2);
ctx.drawImage(canvas, 0, 0, canvas.width / 2, canvas.height / 2, 0, 0, canvas.width, canvas.height);
https://github.com/nodeca/glur - it implements gaussian blur via IIR filter. See demos.