Skip to content

Commit

Permalink
Add filter for crossOrigin image transforms (#28255)
Browse files Browse the repository at this point in the history
Add `media.crossOrigin` filter to allow cross-origin images to be used in a canvas.

Co-authored-by: Jon Surrell <jon.surrell@automattic.com>
Co-authored-by: Bart <bartlomiej.kalisz@gmail.com>
  • Loading branch information
3 people authored Jan 27, 2021
1 parent 30fafd0 commit d5f58c6
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
24 changes: 24 additions & 0 deletions docs/designers-developers/developers/filters/block-filters.md
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,30 @@ wp.hooks.addFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-nam
```
{% end %}

#### `media.crossOrigin`

Used to set or modify the `crossOrigin` attribute for foreign-origin media elements (i.e `<img>`, `<audio>` , `<img>` , `<link>` , `<script>`, `<video>`). See this [article](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) for more information the `crossOrigin` attribute, its values and how it applies to each element.

One example of it in action is in the Image block's transform feature to allow cross-origin images to be used in a `<canvas>`.

_Example:_

```js
addFilter(
'media.crossOrigin',
'my-plugin/with-cors-media',
// The callback accepts a second `mediaSrc` argument which references
// the url to actual foreign media, useful if you want to decide
// the value of crossOrigin based upon it.
( crossOrigin, mediaSrc ) => {
if ( mediaSrc.startsWith( 'https://example.com' ) ) {
return 'use-credentials';
}
return crossOrigin;
}
);
```

## Removing Blocks

### Using a deny list
Expand Down
4 changes: 4 additions & 0 deletions packages/block-library/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### New Features

- Allow setting the `crossOrigin` attribute so the `useTransformImage` hook can use cross-origin sources ([#28255](https://github.com/WordPress/gutenberg/pull/28255/)).

## 2.27.0 (2020-12-17)

### Enhancement
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
* WordPress dependencies
*/
import { useCallback, useEffect, useMemo, useState } from '@wordpress/element';
import { applyFilters } from '@wordpress/hooks';

function useTransformState( { url, naturalWidth, naturalHeight } ) {
const [ editedUrl, setEditedUrl ] = useState();
Expand Down Expand Up @@ -90,6 +91,15 @@ function useTransformState( { url, naturalWidth, naturalHeight } ) {
const el = new window.Image();
el.src = url;
el.onload = editImage;

const imgCrossOrigin = applyFilters(
'media.crossOrigin',
undefined,
url
);
if ( typeof imgCrossOrigin === 'string' ) {
el.crossOrigin = imgCrossOrigin;
}
}, [
rotation,
naturalWidth,
Expand Down

0 comments on commit d5f58c6

Please sign in to comment.