how to slice an image in css - javascript

I want to slice images in my html document using CSS.
Here is how I want to slice the image. I've masked it with red color:
<div class="img_section" >
<img src="http://i62.tinypic.com/1zbcqhg.jpg" alt="sliced-image" >
</div>
I don't want to use a mask layer to hide the image, because the background of document is not a solid color. I used border-radius property to do it but I couldn't. If it's not possible with CSS , so isn't it possible with js too?

You could do this using svg's clipPath to clip the image and foreignObjectto import the html within svg, since you could only apply svg clipPath to a svg element.
<svg width="445" height="257">
<clipPath id="clip">
<path d="M0,0 h444 l-130,257 h-314z" />
</clipPath>
<foreignObject clip-path="url(#clip)" width="445" height="257">
<div class="img_section">
<img src="http://i62.tinypic.com/1zbcqhg.jpg" alt="sliced-image" />
</div>
</foreignObject>
</svg>

You can do that with CSS layer max, I wrote an example to create what you want, overlayed with black mask.
HTML Code:
<div class="img_section" >
<img src="http://i62.tinypic.com/1zbcqhg.jpg" alt="sliced-image" >
<div class="image-arrow"></div>
</div>
CSS:
.img_section{
width:445;
height:257px;
position:absolute;
}
.image-arrow{
width: 0;
height: 0;
border-bottom: 257px solid black;
border-left: 130px solid transparent;
position:absolute;
right: 0;
bottom: 0;
}

There is no such way in CSS to slice the images this can only be done in LESS and SASS but you can use multiple images as a sprite (single image multiple icon)
Check this out

I'm not certain, but I think you may be looking for clip-path: https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path
Browser support is rather patchy (as of July 2015), however. http://caniuse.com/#search=clip-path

Related

How can I access an SVG element embedded in a CSS `background` from JavaScript?

Given this HTML and CSS that embeds an SVG as a background:
<div class="box"></div>
.box {
width: 300px;
height: 200px;
background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><rect id="rect" width="100" height="100" fill="red"><animate attributeName="x" from="0" to="400" dur="6s" repeatCount="indefinite"/></rect></svg>');
}
I want to use JavaScript to access #rect like so:
// Wait for the SVG to load.
window.onload = function() {
// ...but this still logs null
console.log(document.getElementById("rect"));
}
But this prints null in the console. Is there any way to get a reference to this <rect> via JavaScript?
When loaded as a CSS <image> (like through background-image but also through content and other CSS properties), your SVG document is loaded in an external environment, that scripts don't have access to, just like it is in an HTML <img> by the way.
For all that matters you can even forget there is an SVG Document loaded at all here.
If you want to modify the image, you need to edit the URL directly:
const box = document.querySelector(".box");
// rule is a string
const rule = getComputedStyle(box).backgroundImage;
box.style.backgroundImage = rule.replace("red", "blue");
.box {
width: 300px;
height: 200px;
background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><rect id="rect" width="100" height="100" fill="red"><animate attributeName="x" from="0" to="400" dur="6s" repeatCount="indefinite"/></rect></svg>');
}
<div class="box"></div>

Any workaround to this Firefox bug? SVGElement.getScreenCTM incorrect when parent element has a transform

The Firefox bug in question is https://bugzilla.mozilla.org/show_bug.cgi?id=1610093
It's a long-standing issue whereby the getScreenCTM method of an SVG element returns incorrect values when a parent above the root SVG element has a transform applied.
The following snippet should show the black circle directly under the mouse pointer inside the red box. This works correctly in webkit/blink where the css transform on the parent is properly calculated. In Firefox this bug causes the black circle to be offset by the same values as the css transform on the parent div element.
I've avoided the issue up until now by ensuring there are no transforms further up the dom tree, but I'm now developing this as a component where I won't have control over the parent dom.
Does anyone know an easy workaround for getting a correct transform matrix?
const svgEl = document.querySelector(`svg#test-1`);
const circleEl = document.querySelector(`svg#test-1 circle`);
const handleMouseMove = (e) => {
// transform screen to SVG coordinate space
const mousePoint = svgEl.createSVGPoint();
mousePoint.x = e.clientX;
mousePoint.y = e.clientY;
const mouseCoordsInCanvasSpace = mousePoint.matrixTransform(svgEl.getScreenCTM().inverse())
// set circle to coords, should be mouse center in SVG coord space
circleEl.setAttributeNS(null, 'cx', mouseCoordsInCanvasSpace.x);
circleEl.setAttributeNS(null, 'cy', mouseCoordsInCanvasSpace.y);
}
window.addEventListener('mousemove', handleMouseMove);
body{
padding: 0px;
margin: 0px;
}
svg {
border: 2px solid red;
margin-left: 0px;
}
<!DOCTYPE html>
<html>
<body>
<div style="transform: translate(50px, 50px);">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100" id="test-1">
<circle r="10" />
</svg>
</div>
</body>
</html>
That is an annoying bug! My suggestion is to use an <object> element. The source/data for the object should be the SVG.
In the following example I'm using a data URL as a data source for the <object>, so that we at least can see something here on ST. But I imagine that the SVG should be dynamic somehow. So, to make this work you will need to load the SVG as a source of a file (data="/file.svg"). If you do that you have access to the contentDocument property on <object> and in that way you have direct access to the DOM of the SVG from the "outside". It needs to run from a web server and on the same domain as well.
body{
padding: 0px;
margin: 0px;
}
object {
border: 2px solid red;
margin-left: 0px;
}
<div style="transform: translate(50px, 50px);">
<object width="100" height="100" type="image/svg+xml" data="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMDAgMTAwIiB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgaWQ9InRlc3QtMSI+CjxzY3JpcHQgdHlwZT0idGV4dC9qYXZhc2NyaXB0Ij4KPCFbQ0RBVEFbCnZhciBjaXJjbGVFbDsKY29uc3QgaGFuZGxlTW91c2VNb3ZlID0gZSA9PiB7CiAgY29uc3QgbW91c2VQb2ludCA9IG5ldyBET01Qb2ludChlLmNsaWVudFgsIGUuY2xpZW50WSk7ICAKICBjb25zdCBtb3VzZUNvb3Jkc0luQ2FudmFzU3BhY2UgPSBtb3VzZVBvaW50Lm1hdHJpeFRyYW5zZm9ybShlLnRhcmdldC5nZXRTY3JlZW5DVE0oKS5pbnZlcnNlKCkpOwogIC8vIHNldCBjaXJjbGUgdG8gY29vcmRzLCBzaG91bGQgYmUgbW91c2UgY2VudGVyIGluIFNWRyBjb29yZCBzcGFjZSAKICBjaXJjbGVFbC5zZXRBdHRyaWJ1dGVOUyhudWxsLCAnY3gnLCBtb3VzZUNvb3Jkc0luQ2FudmFzU3BhY2UueCk7CiAgY2lyY2xlRWwuc2V0QXR0cmlidXRlTlMobnVsbCwgJ2N5JywgbW91c2VDb29yZHNJbkNhbnZhc1NwYWNlLnkpOwp9OwoKZG9jdW1lbnQuYWRkRXZlbnRMaXN0ZW5lcignRE9NQ29udGVudExvYWRlZCcsIGUgPT4gewogIGNpcmNsZUVsID0gZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoJ2MxJyk7CiAgZG9jdW1lbnQuYWRkRXZlbnRMaXN0ZW5lcignbW91c2Vtb3ZlJywgaGFuZGxlTW91c2VNb3ZlKTsKfSk7Cl1dPgo8L3NjcmlwdD4KPGNpcmNsZSBpZD0iYzEiIHI9IjEwIiAvPgo8L3N2Zz4="></object>
</div>
Here is the SVG I use in the <object>:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<script type="text/javascript">
<![CDATA[
var circleEl;
const handleMouseMove = e => {
const mousePoint = new DOMPoint(e.clientX, e.clientY);
const mouseCoordsInCanvasSpace = mousePoint.matrixTransform(e.target.getScreenCTM().inverse());
circleEl.setAttributeNS(null, 'cx', mouseCoordsInCanvasSpace.x);
circleEl.setAttributeNS(null, 'cy', mouseCoordsInCanvasSpace.y);
};
document.addEventListener('DOMContentLoaded', e => {
circleEl = document.getElementById('c1');
document.addEventListener('mousemove', handleMouseMove);
});
]]>
</script>
<circle id="c1" r="10" />
</svg>

d3 transition SVG polygon animation not smooth in Firefox

I'm using d3 to animate an SVG polygon as follows...
https://jsfiddle.net/p6jy5t0n/35/
It's smooth on Chrome/Safari but horribly jerky on Firefox - the star even seems to dance around in terms of its positioning changing.
The code in question simply relies on chaining d3's transitions to make the star grow then shrink back to normal by increasing it's stroke-width...
d3.select(".svgStar").transition().duration(500).ease("easeElastic")
.each("end",function(){
d3.select(this).transition().duration(500).ease("easeElastic")
.style("stroke-width","0.1px")
.style("fill",starCol);
})
.style("stroke-width","2.5px")
.style("fill","#fff400");
Any ideas what could be done to get a smoother transition in Firefox?
Have you tried with D3v5. The easeElastic behaves different in Chrome compared to D3v3.
Do you know what easeElastic does to the transition?
Try d3.easeLinear for comparision.
function transformStar(){
var starCol = d3.select(".svgStar").style("fill");
var starAnimationDuration = 500;
d3.select(".svgStar").style("stroke","rgb(255, 218, 93)");
d3.select(".svgStar")
.transition().duration(starAnimationDuration).ease(d3.easeElastic)
.style("stroke-width","2.5px")
.style("fill","#fff400")
.transition().duration(starAnimationDuration).ease(d3.easeElastic)
.style("stroke-width","0.1px")
.style("fill",starCol);
}
<script src="https://d3js.org/d3.v5.min.js" charset="utf-8"></script>
<div id="container">
<svg>
<g id="starG" style="transform:translateX(50px)">
<polygon class="svgStar" fill="#ffda5d" stroke="none" w="9" cursor="default" points="94,20 101,43 125,43 106,58 113,80 94,66 74,80 80,58 62,43 86,43" style="transform: translate(-94px, 18px);">
</polygon>
<text x="0" y="74" id="starTxt" style="cursor: default; font-size: 12px; font-weight: bold; text-anchor: middle; fill: rgb(20, 171, 20); stroke-width: 0px;">
Go!
</text>
</g>
</svg>
</div>
<button onclick="transformStar();">
Transform Star!
</button>

How can I animate a SVG who is not hard coded?

I can't animate a svg that I import using the img tag. I can't hard code the svg, as my project generates it during pre-processing using webpack. Sadly, it doesn't seems like I could fetch my file through the svg tag, as I'm not aware of any "src" or "href" attribute.
How can I animate a SVG who is not hard coded ?
That really depends on how is powered your animation.
There are basically three ways to generate an animated SVG:
SMIL Animation - unfortunately not really widely supported (but you did tag with [svg-animate], so let's take it as the first case).
CSS Animation - With the emergence of SVG2, I bet these will become more and more common.
Script based Animations.
How do these behave when their <svg> documentElement is embedded in an <img> tag?
SMIL animations in <img>.
In supporting browsers, these would run just normally, as if your SVG was not embedded.
The only restrictions you would face are
You wouldn't receive any user-gesture, so the element.click and alike events won't work
You can't fallback to a script based animation for browsers that don't support SMIL animations (IE...).
Both limitations do not affect SVG loaded in <object>, <embed> or <iframe>, so you could well use it instead if you need it.
var svgStr = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" width="50" height="50">
<rect id="rect" x="-30" y="0" width="30" height="50">
<!-- this will work normally, even in an <img> -->
<animate attributeType="XML" attributeName="x" from="-30" to="50"
begin="0s" dur="10s" repeatCount="indefinite"/>
<!-- this will not work in <img>, but will in <object>/<iframe>/<embed> -->
<animate attributeType="XML" attributeName="fill" from="blue" to="red"
begin="rect.click"
dur="1s" repeatCount="1"/>
</rect>
<!-- js-based workaround won't work in <img> but will in <object>/<iframe>/<embed> -->
<script src="https://cdn.rawgit.com/FakeSmile/FakeSmile/23c5ceae/smil.user.js"><\/script>
</svg>`;
loadSVG(document.images[0]);
loadSVG(document.querySelector('object'));
function loadSVG(container) {
var url = URL.createObjectURL(new Blob([svgStr], {type: 'image/svg+xml'}));
container.src = container.data = url;
}
img{
border: 1px solid green;
}
object{
border: 1px solid blue;
}
<img src="">
<object></object>
<div>Try to click the black rectangle in both the <code><img></code> and <code><object></code> tags.
CSS Animations in <img>.
Just like SMIL animations, they should work in supporting browsers, with the same user-gesture limitations, and the same possible ways around (use an other container):
var svgStr = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" width="50" height="50">
<rect id="rect" x="0" y="0" width="30" height="50"/>
<defs>
<style>
#rect {
/* this will work normally, even in an img */
animation: move 10s linear infinite;
}
#rect:hover {
/* this will not work in img, but will in object/iframe/embed */
animation: move 10s linear infinite, color 1s 1;
}
#keyframes move {
from {
transform: translate(-30px, 0px);
}
to {
transform: translate(50px, 0px);
}
}
#keyframes color {
from {
fill: blue;
}
to {
fill: red;
}
}
</style>
</defs>
</svg>`;
loadSVG(document.images[0]);
loadSVG(document.querySelector('object'));
function loadSVG(container) {
var url = URL.createObjectURL(new Blob([svgStr], {type: 'image/svg+xml'}));
container.src = container.data = url;
}
img{
border: 1px solid green;
}
object{
border: 1px solid blue;
}
<img src="">
<object></object>
<div>Try to mouse hover the black rectangle in both the <code><img></code> and <code><object></code> tags.
Script based Animations in <img>.
These will simply not work. SVG documents embedded in <img> tag can not be scripted.
To workaround this, use either an <object>, an <embed> or an <iframe> element as container.
var svgStr = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" width="50" height="50">
<rect id="rect" x="0" y="0" width="30" height="50"/>
<script type="application/javascript">
// will simply never work in img
var x = 0, rect = document.getElementById('rect');
function anim() {
x = (x + 1) % 80;
rect.setAttribute('x', x - 30);
requestAnimationFrame(anim);
}
anim();
<\/script>
</svg>`;
loadSVG(document.images[0]);
loadSVG(document.querySelector('object'));
function loadSVG(container) {
var url = URL.createObjectURL(new Blob([svgStr], {type: 'image/svg+xml'}));
container.src = container.data = url;
}
img{
border: 1px solid green;
}
object{
border: 1px solid blue;
}
<img src="">
<object></object>
So basically, SVG in <img> comes with a lot of restrictions, that can all be overwhelmed by using an other container.
Now, every container will come with its own restrictions:
<iframe> will not resize to its content, it will also come by default with a border and some other ugly things.
<object> and <embed> will get unloaded by webkit browsers when not visible (display: none), and won't be cached in any browser...
And of course, there is also the possibility to fetch your SVG markup through AJAX and to load it inside your actual HTML page, but I personally can't advice to do so:
You would need to be sure you don't have duplicate id elements,
You would need to be sure all your CSS rules are specific enough that they won't affect other elements in your page,
You would have to be sure you are loading only trusted code, since scripts will run, that is to say you keep a wide open door to XSS attacks.
And since we're here, an other limitation of SVG in <img> is that it can not load any resources outside its own markup, everything needs to be included in it directly, even fonts and raster images.

Partially fill a shape's border with colour

I am trying to create a progress effect whereby colour fills a DOM object's border (or possibly background). The image attached should give you a better idea of what I'm going for. I have achieved the current result by adding an object with a solid background colour over the grey lines and setting its height. This object has mix-blend-mode: color-burn; applied to it which is why it only colours the grey lines underneath it.
This works okay, but ruins the anti aliasing around the circle, and also the produced colour is unpredictable (changes depending on the colour of the lines).
I feel there must be a better way of achieving this, perhaps with the canvas element. Could someone point me in the right direction please?
Thanks in advance!
This should be possible to do with Canvas and may even be possible with CSS itself by playing with multiple elements etc but I would definitely recommend you to use SVG. SVG offers a lot of benefits in terms of how easy it is to code, maintain and also produce responsive outputs (unlike Canvas which tends to become pixelated when scaled).
The following are the components:
A rect element which is the same size as the parent svg and has a linear-gradient fill. The gradient has two colors - one is the base (light gray) and the other is the progress (cyan-ish).
A mask which is applied on the rect element. The mask has a path which is nothing but the line and the circle. When the mask is applied to the rect, only this path would show through the actual background (or fill) of the rect, the rest of the area would be masked out by the other rect which is added inside the mask.
The mask also has a text element to show the progress value.
The linear-gradient has the stop offset set in such a way that it is equal to the progress. By changing the offset, we can always make sure that the path shows the progress fill only for the required length and the base (light gray) for the rest.
window.onload = function() {
var progress = document.querySelector('#progress'),
base = document.querySelector('#base'),
prgText = document.querySelector('#prg-text'),
prgInput = document.querySelector('#prg-input');
prgInput.addEventListener('change', function() {
prgText.textContent = this.value + '%';
progress.setAttribute('offset', this.value + '%');
base.setAttribute('offset', this.value + '%');
});
}
svg {
width: 200px;
height: 300px;
}
path {
stroke-width: 4;
}
#rect {
fill: url(#grad);
mask: url(#path);
}
/* just for demo */
.controls {
position: absolute;
top: 0;
right: 0;
height: 100px;
line-height: 100px;
border: 1px solid;
}
.controls * {
vertical-align: middle;
}
body {
background-image: radial-gradient(circle, #3F9CBA 0%, #153346 100%);
}
<svg viewBox='0 0 200 300' id='shape-container'>
<linearGradient id='grad' gradientTransform='rotate(90 0 0)'>
<stop offset='50%' stop-color='rgb(0,218,235)' id='progress' />
<stop offset='50%' stop-color='rgb(238,238,238)' id='base' />
</linearGradient>
<mask id='path' maskUnits='userSpaceOnUse' x='0' y='0' width='200' height='300'>
<rect x='0' y='0' width='200' height='300' fill='black' />
<path d='M100,0 100,100 A50,50 0 0,0 100,200 L100,300 M100,200 A50,50 0 1,0 100,100' stroke='white' />
<text id='prg-text' x='100' y='155' font-size='20' text-anchor='middle' fill='white'>50%</text>
</mask>
<rect id='rect' x='0' y='0' width='200' height='300' />
</svg>
<!-- just for demo -->
<div class='controls'>
<label>Set Progress:</label>
<input type='range' id='prg-input' min='0' max='100' value='50' />
</div>
If you are new to SVG you can refer to the MDN Docs (links provided below) for more information about the elements, their attributes and values.
SVG Mask Element
SVG Tutorial on Paths

Categories

Resources