admin管理员组

文章数量:1312905

I have to apply some styles on <img> thanks to a CSS class.

Is it possible to get the dataURL of the <img> with the CSS style ?

$(function() {
  // Original
  const imgOriginal = document.getElementById('original');
  const c1 = document.getElementById('c1');
  let ctx = c1.getContext('2d');
  ctx.drawImage(imgOriginal, 100, 100);

  // Filtered
  const imgFiltered = document.getElementById('filtered');
  const c2 = document.getElementById('c2');
  ctx = c2.getContext('2d');
  ctx.drawImage(imgFiltered, 100, 100);

  // Same dataURL :(
  console.log(c1.toDataURL(), c2.toDataURL());
  console.log(c1.toDataURL() === c2.toDataURL());
})
.filter::before {
  display: block;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
  width: 100%;
  z-index: 1;
  border: 1px solid red;
}

.filter {
  position: relative;
  -webkit-filter: sepia(.5) hue-rotate(-30deg) saturate(1.4);
  filter: sepia(.5) hue-rotate(-30deg) saturate(1.4);
}

canvas {
  display: block;
  width: 100px;
  height: 100px;
  border: 1px solid red;
}
<script src=".1.1/jquery.min.js"></script>


<div>

  <img id="original" src=".jpg/170px-Brad_Pitt_Inglorious_Basterds_Berlin_premiere.jpg">
  <canvas id="c1"></canvas>

  <img id="filtered" class="filter" src=".jpg/170px-Brad_Pitt_Inglorious_Basterds_Berlin_premiere.jpg">
  <canvas id="c2"></canvas>

</div>

I have to apply some styles on <img> thanks to a CSS class.

Is it possible to get the dataURL of the <img> with the CSS style ?

$(function() {
  // Original
  const imgOriginal = document.getElementById('original');
  const c1 = document.getElementById('c1');
  let ctx = c1.getContext('2d');
  ctx.drawImage(imgOriginal, 100, 100);

  // Filtered
  const imgFiltered = document.getElementById('filtered');
  const c2 = document.getElementById('c2');
  ctx = c2.getContext('2d');
  ctx.drawImage(imgFiltered, 100, 100);

  // Same dataURL :(
  console.log(c1.toDataURL(), c2.toDataURL());
  console.log(c1.toDataURL() === c2.toDataURL());
})
.filter::before {
  display: block;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
  width: 100%;
  z-index: 1;
  border: 1px solid red;
}

.filter {
  position: relative;
  -webkit-filter: sepia(.5) hue-rotate(-30deg) saturate(1.4);
  filter: sepia(.5) hue-rotate(-30deg) saturate(1.4);
}

canvas {
  display: block;
  width: 100px;
  height: 100px;
  border: 1px solid red;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div>

  <img id="original" src="https://upload.wikimedia/wikipedia/mons/thumb/c/c7/Brad_Pitt_Inglorious_Basterds_Berlin_premiere.jpg/170px-Brad_Pitt_Inglorious_Basterds_Berlin_premiere.jpg">
  <canvas id="c1"></canvas>

  <img id="filtered" class="filter" src="https://upload.wikimedia/wikipedia/mons/thumb/c/c7/Brad_Pitt_Inglorious_Basterds_Berlin_premiere.jpg/170px-Brad_Pitt_Inglorious_Basterds_Berlin_premiere.jpg">
  <canvas id="c2"></canvas>

</div>

Maybe snippet is going to have a bug because of the <canvas> tag, the idea is there anyway.


EDIT :

If anyone has a suggestion with SVG or something else, I'm using fabricJS.


EDIT 2 (NOT RESOLVE BUT FIND OTHER WAY) :

  1. Thanks to @KavianK. you could replicate CSS style with the canvas context, however to me it's boring because we have to store a different callback for each CSS class to get the dataURL. Working anyway!

  2. Thanks to @Emeeus maybe a solution provide from your backend, not solution for me beacause i'm want to do this ONLY on the front-end. wkhtmltopdf

  3. Thanks to @pegasuspect we can filter an image with SVG, I'm following this way and I replace fabricJS by svgjs, this librairie can replace easly a canvas and it's more easier to work with img and I dind't need the DataURL anymore !

  4. Thanks to @Kaiido there is a way to take a snapshot of your HTML rendered with CSS style with html2canvas easy to get dataURL with this case. Unfortunataly some CSS styles are not supported yet like box-shadow or filter that's why it's not a solution for me

This topic is not resolve but with svgjs I don't need actually work with dataURL.

Share Improve this question edited Nov 11, 2023 at 0:43 Henry Ecker 35.7k19 gold badges46 silver badges64 bronze badges asked Jun 21, 2018 at 15:11 GameTagGameTag 3791 silver badge12 bronze badges 9
  • I think it can't. since you can manipulate the pixels in the canvas, you can implement how you edit the image. – kiro Commented Jun 21, 2018 at 15:31
  • Just to understand, you want to get rid of javascript ? Or you just want the filtering to be done by css classes ? What should be modified in @kavian K. answer in order to be ok for you ? – madjaoue Commented Jun 28, 2018 at 9:09
  • @Mium indeed, I want to know if is it possible to do this without use the canvas's context. I'm trying with SVG at the moment maybe it's a good way : developer.mozilla/en-US/docs/Web/SVG/… – GameTag Commented Jun 28, 2018 at 9:26
  • Well unless your images are svg formatted, I don't think you can export the image+css into a dataUrl without going through canvas. Simply because the bitmap (what is displayed in your screen) is a rendered version, and what you can access through javascript is "raw" data, not bined nor rendered. So the best way today is to use canvas api to capture the bitmap (the rendered version). @Kavian K. answer seems a good solution. – madjaoue Commented Jun 28, 2018 at 9:42
  • Possible duplicate of stackoverflow./questions/49291239/… – Kaiido Commented Jun 29, 2018 at 1:56
 |  Show 4 more ments

4 Answers 4

Reset to default 7

CSS and DOM is a separate world from the bitmaps that are used for images and canvas. The bitmaps themselves are not affected by CSS, only the elements which acts as a looking-glass to the bitmap. So, CSS filters applied to the canvas will not be applied to the image that is produced. You either need to replicate the filters in canvas or rather re apply the same filters to the generated image.

Example:

There is a little known property on the context object, conveniently named filter. This will apply a filter on the context it self. The filter must be set before next draw operation.

var img = new Image();

img.crossOrigin = '';
img.src = document.getElementById( 'original' ).src;

img.onload = function() {
    var canvas = document.getElementById( 'canvas' ),
        ctx = canvas.getContext( '2d' );

    canvas.width = this.width;
    canvas.height = this.height;

    // filter
    if ( typeof ctx.filter !== 'undefined' ) {
        ctx.filter = "sepia(.5) hue-rotate(-30deg) saturate(1.4)";
        ctx.drawImage(this, 0, 0);
    } else {
        ctx.drawImage(this, 0, 0);
    }

    document.getElementById( 'filtered' ).src = canvas.toDataURL();
}
<img id="original" src="https://upload.wikimedia/wikipedia/mons/thumb/c/c7/Brad_Pitt_Inglorious_Basterds_Berlin_premiere.jpg/170px-Brad_Pitt_Inglorious_Basterds_Berlin_premiere.jpg" />
<img id="filtered" />
<canvas id="canvas" style="display: none"></canvas>

tldr;

You can do it with SVG. http://jsfiddle/1hambw93/91/


How to use SVG as a data Source for Images

It is explained here quite nicely. It basically says you can use svg element in src tag of an img.

How to use filters in SVG

It is explained here quite nicely as well: I could achieve the same filter effect with your code, using an SVG filter.

You can generate filter for svg from this site using Sepium to get the same filter as your css. You would have the following SVG so far:

<svg id="test">
    <image xlink:href='https://upload.wikimedia/wikipedia/mons/thumb/c/c7/Brad_Pitt_Inglorious_Basterds_Berlin_premiere.jpg/170px-Brad_Pitt_Inglorious_Basterds_Berlin_premiere.jpg'
      x="0" y="0" height="170px" width="218px" 
      filter='url(#sepium-filter)' />
    <filter id="sepium-filter">
      <feColorMatrix type="matrix" 
        values="1.3 -0.3 1.1   0 0 
                  0  1.3 0.2   0 0 
                  0    0 0.8 0.2 0 
                  0    0   0   1 0">
      </feColorMatrix>
    </filter>
</svg>

Then I used a minimal javascript code to convert to base64 and write the result from the SVG to an object, to display in HTML.

As I understand, You need the puted image, so you need the result of the work made by the browser. To acplish that, you could use wkhtmltopdf specifically wkhtmltoimage. It uses Qt WebKit rendering engine (just like a browser). You have to install that in the server and run somethig like:

wkhtmltoimage  http://mysite/image-Plus-css-PLus-canvas.html myComputedImge.jpg

Where http://mysite/image-Plus-css-PLus-canvas.html is your image in the html with the css, javascript and whatever. All of this of course could be acplished using ajax.

So, using this way you have a .jpg or .png file (myComputedImge.jpg in this case) that has all what you want puted, like a screenshot. If you want the base64 you could do the same as you do with .toDataURL() and the result is the base64 of the image with the css.

If you want to perform this using ajax, you could:

  • Send a request, with the file as parameter or the remote url.
  • If the file is remote the server must be able to reach it.
  • In server side, you create a .html file with the image, the css and javascript or whatever you want.
  • Run the code above detailed to create a .jpg or .png
  • Respond the location of the file created to the ajax request.
  • In the callback, you have the url of the new image with the filters puted.
  • Since you have this new image in server side you could respond the base64 directly instead of the location, then in client side you don't need .toDataURL().

There is 1 work around; It might work for your use case using CSS:

img[src^="data:image/png;"] {
  background-color: #000;
  filter: sepia(50%);
}

This will work for all the images URLs starting with data:image/png

本文标签: javascriptDataURL of an img with CSS classStack Overflow