'cropping image in svelte The first argument is required and must be an <img> or <canvas> element
I am struggling to get cropperjs to work in svelte. Any help would be appreciated.
The svelte script is as follows
<script>
import Cropper from 'cropperjs';
const image = document.getElementById('image');
const cropper = new Cropper(image, {
aspectRatio: 16 / 9,
crop(event) {
console.log(event.detail.x);
console.log(event.detail.y);
console.log(event.detail.width);
console.log(event.detail.height);
console.log(event.detail.rotate);
console.log(event.detail.scaleX);
console.log(event.detail.scaleY);
},
});
</script>
<img id="image" src="./images/favicon.png" alt="">
The error is:
Uncaught Error: The first argument is required and must be an <img> or <canvas> element.
at new Cropper (cropper.js:3229:15)
at instance$1 (Example5.svelte:8:14)
at init (index.mjs:1809:11)
at new Example5 (Example5.svelte:17:36)
at create_fragment (Example5.svelte:17:36)
at init (index.mjs:1824:37)
at new App (Example5.svelte:17:36)
at main.js:3:13
at main.js:7:2
Solution 1:[1]
yes the suggestion by Corrl was spot on. Adding the head elements sorted out the problem. Also the point by haldo, about using onMount is required as well.
Solution 2:[2]
An alternative to initializing Cropper inside onMount would be use:action > Docs > REPL
<svelte:head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/2.0.0-alpha.2/cropper.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/2.0.0-alpha.2/cropper.min.js"></script>
</svelte:head>
<script>
let cropper;
function initCropper(node){
console.log('loaded', node.complete)
cropper = new Cropper(node, {
aspectRatio: 16 / 9,
crop(event) {
console.log(event.detail);
console.log(event.detail.y);
console.log(event.detail.width);
console.log(event.detail.height);
console.log(event.detail.rotate);
console.log(event.detail.scaleX);
console.log(event.detail.scaleY);
},
});
}
</script>
<div>
<img use:initCropper src="https://cdn1-www.dogtime.com/assets/uploads/2011/03/puppy-development.jpg" alt="">
</div>
<style>
img {
display: block;
max-width: 100%;
}
</style>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dram |
| Solution 2 | Corrl |
